Browse Source

save all incoming payments/inoices, listPayments from sql, rm LND paginate payments, refactor constants to typescript

loopout2
Evan Feenstra 4 years ago
parent
commit
71ae6ba306
  1. 5
      dist/src/builtin/index.js
  2. 2
      dist/src/builtin/index.js.map
  3. 10
      dist/src/builtin/mother.js
  4. 2
      dist/src/builtin/mother.js.map
  5. 9
      dist/src/builtin/welcome.js
  6. 2
      dist/src/builtin/welcome.js.map
  7. 88
      dist/src/constants.js
  8. 1
      dist/src/constants.js.map
  9. 22
      dist/src/controllers/api.js
  10. 2
      dist/src/controllers/api.js.map
  11. 26
      dist/src/controllers/bots.js
  12. 2
      dist/src/controllers/bots.js.map
  13. 65
      dist/src/controllers/chatTribes.js
  14. 2
      dist/src/controllers/chatTribes.js.map
  15. 67
      dist/src/controllers/chats.js
  16. 2
      dist/src/controllers/chats.js.map
  17. 28
      dist/src/controllers/confirmations.js
  18. 2
      dist/src/controllers/confirmations.js.map
  19. 19
      dist/src/controllers/contacts.js
  20. 2
      dist/src/controllers/contacts.js.map
  21. 5
      dist/src/controllers/index.js
  22. 2
      dist/src/controllers/index.js.map
  23. 21
      dist/src/controllers/invoices.js
  24. 2
      dist/src/controllers/invoices.js.map
  25. 36
      dist/src/controllers/media.js
  26. 2
      dist/src/controllers/media.js.map
  27. 33
      dist/src/controllers/messages.js
  28. 2
      dist/src/controllers/messages.js.map
  29. 67
      dist/src/controllers/payment.js
  30. 2
      dist/src/controllers/payment.js.map
  31. 15
      dist/src/controllers/subscriptions.js
  32. 2
      dist/src/controllers/subscriptions.js.map
  33. 44
      dist/src/grpc/index.js
  34. 2
      dist/src/grpc/index.js.map
  35. 10
      dist/src/helpers.js
  36. 2
      dist/src/helpers.js.map
  37. 16
      dist/src/hub.js
  38. 2
      dist/src/hub.js.map
  39. 15
      dist/src/network/intercept.js
  40. 2
      dist/src/network/intercept.js.map
  41. 15
      dist/src/network/modify.js
  42. 2
      dist/src/network/modify.js.map
  43. 50
      dist/src/network/receive.js
  44. 2
      dist/src/network/receive.js.map
  45. 22
      dist/src/network/send.js
  46. 2
      dist/src/network/send.js.map
  47. 5
      dist/src/utils/msg.js
  48. 2
      dist/src/utils/msg.js.map
  49. 5
      dist/src/utils/timers.js
  50. 2
      dist/src/utils/timers.js.map
  51. 4
      src/builtin/index.ts
  52. 3
      src/builtin/mother.ts
  53. 5
      src/builtin/welcome.ts
  54. 86
      src/constants.ts
  55. 9
      src/controllers/api.ts
  56. 7
      src/controllers/bots.ts
  57. 4
      src/controllers/chatTribes.ts
  58. 6
      src/controllers/chats.ts
  59. 7
      src/controllers/confirmations.ts
  60. 4
      src/controllers/contacts.ts
  61. 3
      src/controllers/index.ts
  62. 4
      src/controllers/invoices.ts
  63. 2
      src/controllers/media.ts
  64. 8
      src/controllers/messages.ts
  65. 65
      src/controllers/payment.ts
  66. 4
      src/controllers/subscriptions.ts
  67. 42
      src/grpc/index.ts
  68. 3
      src/helpers.ts
  69. 2
      src/hub.ts
  70. 4
      src/network/intercept.ts
  71. 3
      src/network/modify.ts
  72. 31
      src/network/receive.ts
  73. 10
      src/network/send.ts
  74. 3
      src/utils/msg.ts
  75. 4
      src/utils/timers.ts

5
dist/src/builtin/index.js

@ -14,16 +14,15 @@ const SphinxBot = require("sphinx-bot");
const MotherBot = require("./mother"); const MotherBot = require("./mother");
const WelcomeBot = require("./welcome"); const WelcomeBot = require("./welcome");
const LoopBot = require("./loop"); const LoopBot = require("./loop");
const path = require("path");
const models_1 = require("../models"); const models_1 = require("../models");
const bots_1 = require("../controllers/bots"); const bots_1 = require("../controllers/bots");
exports.buildBotPayload = bots_1.buildBotPayload; exports.buildBotPayload = bots_1.buildBotPayload;
const constants = require(path.join(__dirname, '../../config/constants.json')); const constants_1 = require("../constants");
function init() { function init() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
MotherBot.init(); MotherBot.init();
const builtInBots = yield models_1.models.ChatBot.findAll({ where: { const builtInBots = yield models_1.models.ChatBot.findAll({ where: {
botType: constants.bot_types.builtin botType: constants_1.default.bot_types.builtin
} }); } });
if (!(builtInBots && builtInBots.length)) if (!(builtInBots && builtInBots.length))
return; return;

2
dist/src/builtin/index.js.map

@ -1 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/builtin/index.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,mDAAmD;AACnD,wCAAuC;AACvC,sCAAqC;AACrC,wCAAuC;AACvC,kCAAiC;AAEjC,6BAA4B;AAC5B,sCAAkC;AAClC,8CAAmD;AAwBvB,0BAxBpB,sBAAe,CAwBoB;AAtB3C,MAAM,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,6BAA6B,CAAC,CAAC,CAAA;AAE9E,SAAe,IAAI;;QACf,SAAS,CAAC,IAAI,EAAE,CAAA;QAEhB,MAAM,WAAW,GAAG,MAAM,eAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAC,KAAK,EAAC;gBACpD,OAAO,EAAE,SAAS,CAAC,SAAS,CAAC,OAAO;aACvC,EAAC,CAAC,CAAA;QACH,IAAG,CAAC,CAAC,WAAW,IAAI,WAAW,CAAC,MAAM,CAAC;YAAE,OAAM;QAE/C,WAAW,CAAC,OAAO,CAAC,CAAC,CAAA,EAAE;YACnB,IAAG,CAAC,CAAC,SAAS,KAAG,UAAU;gBAAE,UAAU,CAAC,IAAI,EAAE,CAAA;YAC9C,IAAG,CAAC,CAAC,SAAS,KAAG,UAAU;gBAAE,OAAO,CAAC,IAAI,EAAE,CAAA;QAC/C,CAAC,CAAC,CAAA;IACN,CAAC;CAAA;AAQO,oBAAI;AANZ,SAAS,cAAc,CAAC,GAAO;IAC3B,UAAU,CAAC,GAAE,EAAE;QACX,SAAS,CAAC,KAAK,CAAC,SAAS,EAAE,sBAAe,CAAC,GAAG,CAAC,CAAC,CAAA;IACpD,CAAC,EAAC,IAAI,CAAC,CAAA;AACX,CAAC;AAEY,wCAAc"} {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/builtin/index.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,mDAAmD;AACnD,wCAAuC;AACvC,sCAAqC;AACrC,wCAAuC;AACvC,kCAAiC;AAEjC,sCAAkC;AAClC,8CAAmD;AAuBvB,0BAvBpB,sBAAe,CAuBoB;AAtB3C,4CAAoC;AAEpC,SAAe,IAAI;;QACf,SAAS,CAAC,IAAI,EAAE,CAAA;QAEhB,MAAM,WAAW,GAAG,MAAM,eAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAC,KAAK,EAAC;gBACpD,OAAO,EAAE,mBAAS,CAAC,SAAS,CAAC,OAAO;aACvC,EAAC,CAAC,CAAA;QACH,IAAG,CAAC,CAAC,WAAW,IAAI,WAAW,CAAC,MAAM,CAAC;YAAE,OAAM;QAE/C,WAAW,CAAC,OAAO,CAAC,CAAC,CAAA,EAAE;YACnB,IAAG,CAAC,CAAC,SAAS,KAAG,UAAU;gBAAE,UAAU,CAAC,IAAI,EAAE,CAAA;YAC9C,IAAG,CAAC,CAAC,SAAS,KAAG,UAAU;gBAAE,OAAO,CAAC,IAAI,EAAE,CAAA;QAC/C,CAAC,CAAC,CAAA;IACN,CAAC;CAAA;AAQO,oBAAI;AANZ,SAAS,cAAc,CAAC,GAAO;IAC3B,UAAU,CAAC,GAAE,EAAE;QACX,SAAS,CAAC,KAAK,CAAC,SAAS,EAAE,sBAAe,CAAC,GAAG,CAAC,CAAC,CAAA;IACpD,CAAC,EAAC,IAAI,CAAC,CAAA;AACX,CAAC;AAEY,wCAAc"}

10
dist/src/builtin/mother.js

@ -18,17 +18,17 @@ const WelcomeBot = require("./welcome");
const LoopBot = require("./loop"); const LoopBot = require("./loop");
const models_1 = require("../models"); const models_1 = require("../models");
const node_fetch_1 = require("node-fetch"); const node_fetch_1 = require("node-fetch");
const constants_1 = require("../constants");
const msg_types = Sphinx.MSG_TYPE; const msg_types = Sphinx.MSG_TYPE;
const env = process.env.NODE_ENV || 'development'; const env = process.env.NODE_ENV || 'development';
const constants = require(path.join(__dirname, '../../config/constants.json'));
const config = require(path.join(__dirname, '../../config/app.json'))[env]; const config = require(path.join(__dirname, '../../config/app.json'))[env];
const builtinBots = [ const builtinBots = [
'welcome', 'loopout' 'welcome', 'loopout'
]; ];
const builtInBotMsgTypes = { const builtInBotMsgTypes = {
'welcome': [ 'welcome': [
constants.message_types.message, constants_1.default.message_types.message,
constants.message_types.group_join constants_1.default.message_types.group_join
], ],
}; };
const builtInBotNames = { const builtInBotNames = {
@ -74,12 +74,12 @@ function init() {
return message.channel.send({ embed }); return message.channel.send({ embed });
} }
const msgTypes = builtInBotMsgTypes[botName] || [ const msgTypes = builtInBotMsgTypes[botName] || [
constants.message_types.message constants_1.default.message_types.message
]; ];
const chatBot = { const chatBot = {
chatId: chat.id, chatId: chat.id,
botPrefix: '/' + botName, botPrefix: '/' + botName,
botType: constants.bot_types.builtin, botType: constants_1.default.bot_types.builtin,
msgTypes: JSON.stringify(msgTypes), msgTypes: JSON.stringify(msgTypes),
pricePerUse: 0, pricePerUse: 0,
}; };

2
dist/src/builtin/mother.js.map

File diff suppressed because one or more lines are too long

9
dist/src/builtin/welcome.js

@ -12,9 +12,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
const Sphinx = require("sphinx-bot"); const Sphinx = require("sphinx-bot");
const api_1 = require("../controllers/api"); const api_1 = require("../controllers/api");
const models_1 = require("../models"); const models_1 = require("../models");
const path = require("path"); const constants_1 = require("../constants");
const msg_types = Sphinx.MSG_TYPE; const msg_types = Sphinx.MSG_TYPE;
const constants = require(path.join(__dirname, '../../config/constants.json'));
let initted = false; let initted = false;
function init() { function init() {
if (initted) if (initted)
@ -25,7 +24,7 @@ function init() {
client.on(msg_types.MESSAGE, (message) => __awaiter(this, void 0, void 0, function* () { client.on(msg_types.MESSAGE, (message) => __awaiter(this, void 0, void 0, function* () {
const arr = (message.content && message.content.split(' ')) || []; const arr = (message.content && message.content.split(' ')) || [];
console.log('message.type', message.type); console.log('message.type', message.type);
const isGroupJoin = message.type === constants.message_types.group_join; const isGroupJoin = message.type === constants_1.default.message_types.group_join;
console.log('isGroupJoin', isGroupJoin); console.log('isGroupJoin', isGroupJoin);
if (arr.length < 2 && !isGroupJoin) if (arr.length < 2 && !isGroupJoin)
return; return;
@ -39,7 +38,7 @@ function init() {
return; return;
const chatBot = yield models_1.models.ChatBot.findOne({ const chatBot = yield models_1.models.ChatBot.findOne({
where: { where: {
chatId: chat.id, botPrefix: '/welcome', botType: constants.bot_types.builtin chatId: chat.id, botPrefix: '/welcome', botType: constants_1.default.bot_types.builtin
} }
}); });
let meta = 'Welcome to the tribe!'; let meta = 'Welcome to the tribe!';
@ -70,7 +69,7 @@ function init() {
return; return;
const chatBot = yield models_1.models.ChatBot.findOne({ const chatBot = yield models_1.models.ChatBot.findOne({
where: { where: {
chatId: chat.id, botPrefix: '/welcome', botType: constants.bot_types.builtin chatId: chat.id, botPrefix: '/welcome', botType: constants_1.default.bot_types.builtin
} }
}); });
if (!chatBot) if (!chatBot)

2
dist/src/builtin/welcome.js.map

@ -1 +1 @@
{"version":3,"file":"welcome.js","sourceRoot":"","sources":["../../../src/builtin/welcome.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,qCAAoC;AACpC,4CAAgD;AAChD,sCAAkC;AAClC,6BAA4B;AAC5B,MAAM,SAAS,GAAG,MAAM,CAAC,QAAQ,CAAA;AAEjC,MAAM,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,6BAA6B,CAAC,CAAC,CAAA;AAE9E,IAAI,OAAO,GAAG,KAAK,CAAA;AAEnB,SAAgB,IAAI;IAClB,IAAI,OAAO;QAAE,OAAM;IACnB,OAAO,GAAG,IAAI,CAAA;IAEd,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,MAAM,EAAE,CAAA;IAClC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,iBAAW,CAAC,CAAA;IAE9B,MAAM,CAAC,EAAE,CAAC,SAAS,CAAC,OAAO,EAA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,MAAM,IAAI,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;gBAChD,MAAM,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,CAAC,CAAA;gBAC9B,MAAM,QAAQ,GAAG,IAAI,MAAM,CAAC,YAAY,EAAE;qBACvC,SAAS,CAAC,YAAY,CAAC;qBACvB,cAAc,CAAC,uCAAuC,CAAC,CAAA;gBAC1D,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAA;gBACzC,OAAM;YAER;gBACE,MAAM,KAAK,GAAG,IAAI,MAAM,CAAC,YAAY,EAAE;qBACpC,SAAS,CAAC,YAAY,CAAC;qBACvB,QAAQ,CAAC,eAAe,CAAC;qBACzB,SAAS,CAAC;oBACT,EAAE,IAAI,EAAE,qBAAqB,EAAE,KAAK,EAAE,+BAA+B,EAAE;oBACvE,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,eAAe,EAAE;iBACzC,CAAC;qBACD,YAAY,CAAC,MAAM,CAAC,CAAA;gBACvB,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,CAAC,CAAA;gBAC/B,OAAM;SACT;IACH,CAAC,CAAA,CAAC,CAAA;AACJ,CAAC;AA7ED,oBA6EC;AAED,MAAM,MAAM,GAAG;;OAER,CAAA"}

88
dist/src/constants.js

@ -0,0 +1,88 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const constants = {
min_sat_amount: 3,
invite_statuses: {
"pending": 0,
"ready": 1,
"delivered": 2,
"in_progress": 3,
"complete": 4,
"expired": 5,
"payment_pending": 6
},
contact_statuses: {
"pending": 0,
"confirmed": 1
},
statuses: {
"pending": 0,
"confirmed": 1,
"cancelled": 2,
"received": 3,
"failed": 4,
"deleted": 5
},
chat_statuses: {
"approved": 0,
"pending": 1,
"rejected": 2
},
message_types: {
"message": 0,
"confirmation": 1,
"invoice": 2,
"payment": 3,
"cancellation": 4,
"direct_payment": 5,
"attachment": 6,
"purchase": 7,
"purchase_accept": 8,
"purchase_deny": 9,
"contact_key": 10,
"contact_key_confirmation": 11,
"group_create": 12,
"group_invite": 13,
"group_join": 14,
"group_leave": 15,
"group_kick": 16,
"delete": 17,
"repayment": 18,
"member_request": 19,
"member_approve": 20,
"member_reject": 21,
"tribe_delete": 22,
"bot_install": 23,
"bot_cmd": 24,
"bot_res": 25,
"heartbeat": 26,
"heartbeat_confirmation": 27
},
payment_errors: {
"timeout": "Timed Out",
"no_route": "No Route To Receiver",
"error": "Error",
"incorrect_payment_details": "Incorrect Payment Details",
"unknown": "Unknown"
},
chat_types: {
"conversation": 0,
"group": 1,
"tribe": 2
},
bot_types: {
"builtin": 0,
"local": 1,
"remote": 2
},
chat_roles: {
"-": 0,
"owner": 1,
"admin": 2,
"mod": 3,
"writer": 4,
"reader": 5
}
};
exports.default = constants;
//# sourceMappingURL=constants.js.map

1
dist/src/constants.js.map

@ -0,0 +1 @@
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":";;AAAA,MAAM,SAAS,GAAG;IAChB,cAAc,EAAE,CAAC;IACjB,eAAe,EAAE;QACf,SAAS,EAAE,CAAC;QACZ,OAAO,EAAE,CAAC;QACV,WAAW,EAAE,CAAC;QACd,aAAa,EAAE,CAAC;QAChB,UAAU,EAAE,CAAC;QACb,SAAS,EAAE,CAAC;QACZ,iBAAiB,EAAE,CAAC;KACrB;IACD,gBAAgB,EAAE;QAChB,SAAS,EAAE,CAAC;QACZ,WAAW,EAAE,CAAC;KACf;IACD,QAAQ,EAAE;QACR,SAAS,EAAE,CAAC;QACZ,WAAW,EAAE,CAAC;QACd,WAAW,EAAE,CAAC;QACd,UAAU,EAAE,CAAC;QACb,QAAQ,EAAE,CAAC;QACX,SAAS,EAAE,CAAC;KACb;IACD,aAAa,EAAE;QACb,U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AE,CAAC;QACX,QAAQ,EAAE,CAAC;KACZ;CACF,CAAA;AAED,kBAAe,SAAS,CAAA"}

22
dist/src/controllers/api.js

@ -9,7 +9,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}); });
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const path = require("path");
const network = require("../network"); const network = require("../network");
const models_1 = require("../models"); const models_1 = require("../models");
const short = require("short-uuid"); const short = require("short-uuid");
@ -17,11 +16,7 @@ const rsa = require("../crypto/rsa");
const jsonUtils = require("../utils/json"); const jsonUtils = require("../utils/json");
const socket = require("../utils/socket"); const socket = require("../utils/socket");
const res_1 = require("../utils/res"); const res_1 = require("../utils/res");
/* const constants_1 = require("../constants");
hexdump -n 8 -e '4/4 "%08X" 1 "\n"' /dev/random
hexdump -n 16 -e '4/4 "%08X" 1 "\n"' /dev/random
*/
const constants = require(path.join(__dirname, '../../config/constants.json'));
function processAction(req, res) { function processAction(req, res) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
console.log('=> processAction', req.body); console.log('=> processAction', req.body);
@ -96,7 +91,7 @@ function finalAction(a, bot_id) {
const topic = `${dest}/${myBot.uuid}`; const topic = `${dest}/${myBot.uuid}`;
const data = { const data = {
action, bot_id, bot_name, action, bot_id, bot_name,
type: constants.message_types.bot_res, type: constants_1.default.message_types.bot_res,
message: { content: a.content, amount: amount || 0 }, message: { content: a.content, amount: amount || 0 },
chat: { uuid: chat_uuid }, chat: { uuid: chat_uuid },
sender: { sender: {
@ -117,12 +112,11 @@ function finalAction(a, bot_id) {
if (!(pubkey && pubkey.length === 66 && amount)) { if (!(pubkey && pubkey.length === 66 && amount)) {
throw 'wrong params'; throw 'wrong params';
} }
const MIN_SATS = 3;
const destkey = pubkey; const destkey = pubkey;
const opts = { const opts = {
dest: destkey, dest: destkey,
data: {}, data: {},
amt: Math.max((amount || 0), MIN_SATS) amt: Math.max((amount || 0), constants_1.default.min_sat_amount)
}; };
try { try {
yield network.signAndSend(opts); yield network.signAndSend(opts);
@ -138,7 +132,7 @@ function finalAction(a, bot_id) {
throw 'no content'; throw 'no content';
if (!theChat) if (!theChat)
throw 'no chat'; throw 'no chat';
if (!theChat.type === constants.chat_types.tribe) if (theChat.type !== constants_1.default.chat_types.tribe)
throw 'not a tribe'; throw 'not a tribe';
const encryptedForMeText = rsa.encrypt(owner.contactKey, content); const encryptedForMeText = rsa.encrypt(owner.contactKey, content);
const encryptedText = rsa.encrypt(theChat.groupKey, content); const encryptedText = rsa.encrypt(theChat.groupKey, content);
@ -150,13 +144,13 @@ function finalAction(a, bot_id) {
const msg = { const msg = {
chatId: theChat.id, chatId: theChat.id,
uuid: short.generate(), uuid: short.generate(),
type: constants.message_types.bot_res, type: constants_1.default.message_types.bot_res,
sender: botContactId, sender: botContactId,
amount: amount || 0, amount: amount || 0,
date: date, date: date,
messageContent: encryptedForMeText, messageContent: encryptedForMeText,
remoteMessageContent: JSON.stringify(textMap), remoteMessageContent: JSON.stringify(textMap),
status: constants.statuses.confirmed, status: constants_1.default.statuses.confirmed,
createdAt: date, createdAt: date,
updatedAt: date, updatedAt: date,
senderAlias: alias, senderAlias: alias,
@ -168,9 +162,9 @@ function finalAction(a, bot_id) {
}); });
yield network.sendMessage({ yield network.sendMessage({
chat: theChat, chat: theChat,
sender: Object.assign(Object.assign({}, owner.dataValues), { alias, id: botContactId, role: constants.chat_roles.reader }), sender: Object.assign(Object.assign({}, owner.dataValues), { alias, id: botContactId, role: constants_1.default.chat_roles.reader }),
message: { content: textMap, id: message.id, uuid: message.uuid }, message: { content: textMap, id: message.id, uuid: message.uuid },
type: constants.message_types.bot_res, type: constants_1.default.message_types.bot_res,
success: () => ({ success: true }), success: () => ({ success: true }),
failure: (e) => { failure: (e) => {
throw e; throw e;

2
dist/src/controllers/api.js.map

File diff suppressed because one or more lines are too long

26
dist/src/controllers/bots.js

@ -9,7 +9,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}); });
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const path = require("path");
const tribes = require("../utils/tribes"); const tribes = require("../utils/tribes");
const crypto = require("crypto"); const crypto = require("crypto");
const models_1 = require("../models"); const models_1 = require("../models");
@ -20,7 +19,7 @@ const api_1 = require("./api");
const socket = require("../utils/socket"); const socket = require("../utils/socket");
const node_fetch_1 = require("node-fetch"); const node_fetch_1 = require("node-fetch");
const SphinxBot = require("sphinx-bot"); const SphinxBot = require("sphinx-bot");
const constants = require(path.join(__dirname, '../../config/constants.json')); const constants_1 = require("../constants");
exports.getBots = (req, res) => __awaiter(void 0, void 0, void 0, function* () { exports.getBots = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
try { try {
const bots = yield models_1.models.Bot.findAll(); const bots = yield models_1.models.Bot.findAll();
@ -88,10 +87,10 @@ function installBotAsTribeAdmin(chat, bot_json) {
return console.log('=> only tribe owner can install bots'); return console.log('=> only tribe owner can install bots');
const { uuid, owner_pubkey, unique_name, price_per_use } = bot_json; const { uuid, owner_pubkey, unique_name, price_per_use } = bot_json;
const isLocal = owner_pubkey === owner.publicKey; const isLocal = owner_pubkey === owner.publicKey;
let botType = constants.bot_types.remote; let botType = constants_1.default.bot_types.remote;
if (isLocal) { if (isLocal) {
console.log('=> install local bot now!'); console.log('=> install local bot now!');
botType = constants.bot_types.local; botType = constants_1.default.bot_types.local;
} }
const chatBot = { const chatBot = {
chatId, chatId,
@ -109,13 +108,13 @@ function installBotAsTribeAdmin(chat, bot_json) {
if (myBot) { if (myBot) {
yield models_1.models.ChatBot.create(chatBot); yield models_1.models.ChatBot.create(chatBot);
postToBotServer({ postToBotServer({
type: constants.message_types.bot_install, type: constants_1.default.message_types.bot_install,
bot_uuid: myBot.uuid, bot_uuid: myBot.uuid,
message: { content: '', amount: 0 }, message: { content: '', amount: 0 },
sender: { sender: {
pub_key: owner.publicKey, pub_key: owner.publicKey,
alias: owner.alias, alias: owner.alias,
role: constants.chat_roles.owner role: constants_1.default.chat_roles.owner
}, },
chat: { uuid: chat_uuid } chat: { uuid: chat_uuid }
}, myBot, SphinxBot.MSG_TYPE.INSTALL); }, myBot, SphinxBot.MSG_TYPE.INSTALL);
@ -137,7 +136,7 @@ function installBotAsTribeAdmin(chat, bot_json) {
exports.installBotAsTribeAdmin = installBotAsTribeAdmin; exports.installBotAsTribeAdmin = installBotAsTribeAdmin;
function keysendBotInstall(b, chat_uuid) { function keysendBotInstall(b, chat_uuid) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
return yield botKeysend(constants.message_types.bot_install, b.botUuid, b.botMakerPubkey, b.pricePerUse, chat_uuid); return yield botKeysend(constants_1.default.message_types.bot_install, b.botUuid, b.botMakerPubkey, b.pricePerUse, chat_uuid);
}); });
} }
exports.keysendBotInstall = keysendBotInstall; exports.keysendBotInstall = keysendBotInstall;
@ -145,7 +144,7 @@ function keysendBotCmd(msg, b) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const amount = msg.message.amount || 0; const amount = msg.message.amount || 0;
const amt = Math.max(amount, b.pricePerUse); const amt = Math.max(amount, b.pricePerUse);
return yield botKeysend(constants.message_types.bot_cmd, b.botUuid, b.botMakerPubkey, amt, msg.chat.uuid, msg.message.content, (msg.sender && msg.sender.role)); return yield botKeysend(constants_1.default.message_types.bot_cmd, b.botUuid, b.botMakerPubkey, amt, msg.chat.uuid, msg.message.content, (msg.sender && msg.sender.role));
}); });
} }
exports.keysendBotCmd = keysendBotCmd; exports.keysendBotCmd = keysendBotCmd;
@ -153,8 +152,7 @@ function botKeysend(msg_type, bot_uuid, botmaker_pubkey, amount, chat_uuid, cont
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const owner = yield models_1.models.Contact.findOne({ where: { isOwner: true } }); const owner = yield models_1.models.Contact.findOne({ where: { isOwner: true } });
const dest = botmaker_pubkey; const dest = botmaker_pubkey;
const MIN_SATS = 3; const amt = Math.max(amount || constants_1.default.min_sat_amount);
const amt = Math.max(amount || MIN_SATS);
const opts = { const opts = {
amt, amt,
dest, dest,
@ -166,7 +164,7 @@ function botKeysend(msg_type, bot_uuid, botmaker_pubkey, amount, chat_uuid, cont
sender: { sender: {
pub_key: owner.publicKey, pub_key: owner.publicKey,
alias: owner.alias, alias: owner.alias,
role: sender_role || constants.chat_roles.reader role: sender_role || constants_1.default.chat_roles.reader
} }
} }
}; };
@ -285,7 +283,7 @@ function buildBotPayload(msg) {
roles: [] roles: []
} }
}; };
if (msg.sender.role === constants.chat_roles.owner) { if (msg.sender.role === constants_1.default.chat_roles.owner) {
if (m.member) if (m.member)
m.member.roles = [{ m.member.roles = [{
name: 'Admin' name: 'Admin'
@ -341,12 +339,12 @@ function receiveBotRes(payload) {
const msg = { const msg = {
chatId: chat.id, chatId: chat.id,
uuid: msg_uuid, uuid: msg_uuid,
type: constants.message_types.bot_res, type: constants_1.default.message_types.bot_res,
sender: (sender && sender.id) || 0, sender: (sender && sender.id) || 0,
amount: amount || 0, amount: amount || 0,
date: date, date: date,
messageContent: content, messageContent: content,
status: constants.statuses.confirmed, status: constants_1.default.statuses.confirmed,
createdAt: date, createdAt: date,
updatedAt: date, updatedAt: date,
senderAlias: sender_alias || 'Bot', senderAlias: sender_alias || 'Bot',

2
dist/src/controllers/bots.js.map

File diff suppressed because one or more lines are too long

65
dist/src/controllers/chatTribes.js

@ -17,11 +17,10 @@ const rsa = require("../crypto/rsa");
const helpers = require("../helpers"); const helpers = require("../helpers");
const socket = require("../utils/socket"); const socket = require("../utils/socket");
const tribes = require("../utils/tribes"); const tribes = require("../utils/tribes");
const path = require("path");
const hub_1 = require("../hub"); const hub_1 = require("../hub");
const msg_1 = require("../utils/msg"); const msg_1 = require("../utils/msg");
const sequelize_1 = require("sequelize"); const sequelize_1 = require("sequelize");
const constants = require(path.join(__dirname, '../../config/constants.json')); const constants_1 = require("../constants");
function joinTribe(req, res) { function joinTribe(req, res) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
console.log('=> joinTribe'); console.log('=> joinTribe');
@ -61,8 +60,8 @@ function joinTribe(req, res) {
let date = new Date(); let date = new Date();
date.setMilliseconds(0); date.setMilliseconds(0);
const chatStatus = is_private ? const chatStatus = is_private ?
constants.chat_statuses.pending : constants_1.default.chat_statuses.pending :
constants.chat_statuses.approved; constants_1.default.chat_statuses.approved;
const chatParams = { const chatParams = {
uuid: uuid, uuid: uuid,
contactIds: JSON.stringify(contactIds), contactIds: JSON.stringify(contactIds),
@ -70,7 +69,7 @@ function joinTribe(req, res) {
createdAt: date, createdAt: date,
updatedAt: date, updatedAt: date,
name: name, name: name,
type: constants.chat_types.tribe, type: constants_1.default.chat_types.tribe,
host: host || tribes.getHost(), host: host || tribes.getHost(),
groupKey: group_key, groupKey: group_key,
ownerPubkey: owner_pubkey, ownerPubkey: owner_pubkey,
@ -79,8 +78,8 @@ function joinTribe(req, res) {
priceToJoin: amount || 0, priceToJoin: amount || 0,
}; };
const typeToSend = is_private ? const typeToSend = is_private ?
constants.message_types.member_request : constants_1.default.message_types.member_request :
constants.message_types.group_join; constants_1.default.message_types.group_join;
const contactIdsToSend = is_private ? const contactIdsToSend = is_private ?
[theTribeOwner.id] : // ONLY SEND TO TRIBE OWNER IF ITS A REQUEST [theTribeOwner.id] : // ONLY SEND TO TRIBE OWNER IF ITS A REQUEST
chatParams.contactIds; chatParams.contactIds;
@ -106,9 +105,9 @@ function joinTribe(req, res) {
models_1.models.ChatMember.create({ models_1.models.ChatMember.create({
contactId: theTribeOwner.id, contactId: theTribeOwner.id,
chatId: chat.id, chatId: chat.id,
role: constants.chat_roles.owner, role: constants_1.default.chat_roles.owner,
lastActive: date, lastActive: date,
status: constants.chat_statuses.approved status: constants_1.default.chat_statuses.approved
}); });
res_1.success(res, jsonUtils.chatToJson(chat)); res_1.success(res, jsonUtils.chatToJson(chat));
}); });
@ -124,7 +123,7 @@ function receiveMemberRequest(payload) {
const chat = yield models_1.models.Chat.findOne({ where: { uuid: chat_uuid } }); const chat = yield models_1.models.Chat.findOne({ where: { uuid: chat_uuid } });
if (!chat) if (!chat)
return console.log('no chat'); return console.log('no chat');
const isTribe = chat_type === constants.chat_types.tribe; const isTribe = chat_type === constants_1.default.chat_types.tribe;
if (!isTribe || !isTribeOwner) if (!isTribe || !isTribeOwner)
return console.log('not a tribe'); return console.log('not a tribe');
var date = new Date(); var date = new Date();
@ -153,8 +152,8 @@ function receiveMemberRequest(payload) {
console.log("UPSERT", { console.log("UPSERT", {
contactId: theSender.id, contactId: theSender.id,
chatId: chat.id, chatId: chat.id,
role: constants.chat_roles.reader, role: constants_1.default.chat_roles.reader,
status: constants.chat_statuses.pending, status: constants_1.default.chat_statuses.pending,
lastActive: date, lastActive: date,
}); });
// maybe check here manually???? // maybe check here manually????
@ -162,18 +161,18 @@ function receiveMemberRequest(payload) {
yield models_1.models.ChatMember.upsert({ yield models_1.models.ChatMember.upsert({
contactId: theSender.id, contactId: theSender.id,
chatId: chat.id, chatId: chat.id,
role: constants.chat_roles.reader, role: constants_1.default.chat_roles.reader,
status: constants.chat_statuses.pending, status: constants_1.default.chat_statuses.pending,
lastActive: date, lastActive: date,
}); });
} }
catch (e) { } catch (e) { }
const msg = { const msg = {
chatId: chat.id, chatId: chat.id,
type: constants.message_types.member_request, type: constants_1.default.message_types.member_request,
sender: (theSender && theSender.id) || 0, sender: (theSender && theSender.id) || 0,
messageContent: '', remoteMessageContent: '', messageContent: '', remoteMessageContent: '',
status: constants.statuses.confirmed, status: constants_1.default.statuses.confirmed,
date: date, createdAt: date, updatedAt: date date: date, createdAt: date, updatedAt: date
}; };
if (isTribe) { if (isTribe) {
@ -275,11 +274,11 @@ function approveOrRejectMember(req, res) {
if (!msgId || !contactId || !(status === 'approved' || status === 'rejected')) { if (!msgId || !contactId || !(status === 'approved' || status === 'rejected')) {
return res_1.failure(res, 'incorrect status'); return res_1.failure(res, 'incorrect status');
} }
let memberStatus = constants.chat_statuses.rejected; let memberStatus = constants_1.default.chat_statuses.rejected;
let msgType = constants.message_types.member_reject; let msgType = constants_1.default.message_types.member_reject;
if (status === 'approved') { if (status === 'approved') {
memberStatus = constants.chat_statuses.approved; memberStatus = constants_1.default.chat_statuses.approved;
msgType = constants.message_types.member_approve; msgType = constants_1.default.message_types.member_approve;
const contactIds = JSON.parse(chat.contactIds || '[]'); const contactIds = JSON.parse(chat.contactIds || '[]');
if (!contactIds.includes(contactId)) if (!contactIds.includes(contactId))
contactIds.push(contactId); contactIds.push(contactId);
@ -315,15 +314,15 @@ function receiveMemberApprove(payload) {
const { owner, chat, chat_name, sender } = yield helpers.parseReceiveParams(payload); const { owner, chat, chat_name, sender } = yield helpers.parseReceiveParams(payload);
if (!chat) if (!chat)
return console.log('no chat'); return console.log('no chat');
yield chat.update({ status: constants.chat_statuses.approved }); yield chat.update({ status: constants_1.default.chat_statuses.approved });
let date = new Date(); let date = new Date();
date.setMilliseconds(0); date.setMilliseconds(0);
const msg = { const msg = {
chatId: chat.id, chatId: chat.id,
type: constants.message_types.member_approve, type: constants_1.default.message_types.member_approve,
sender: (sender && sender.id) || 0, sender: (sender && sender.id) || 0,
messageContent: '', remoteMessageContent: '', messageContent: '', remoteMessageContent: '',
status: constants.statuses.confirmed, status: constants_1.default.statuses.confirmed,
date: date, createdAt: date, updatedAt: date date: date, createdAt: date, updatedAt: date
}; };
const message = yield models_1.models.Message.create(msg); const message = yield models_1.models.Message.create(msg);
@ -347,7 +346,7 @@ function receiveMemberApprove(payload) {
amount, amount,
sender: owner, sender: owner,
message: {}, message: {},
type: constants.message_types.group_join, type: constants_1.default.message_types.group_join,
}); });
hub_1.sendNotification(chat, chat_name, 'group'); hub_1.sendNotification(chat, chat_name, 'group');
}); });
@ -359,16 +358,16 @@ function receiveMemberReject(payload) {
const { chat, sender, chat_name } = yield helpers.parseReceiveParams(payload); const { chat, sender, chat_name } = yield helpers.parseReceiveParams(payload);
if (!chat) if (!chat)
return console.log('no chat'); return console.log('no chat');
yield chat.update({ status: constants.chat_statuses.rejected }); yield chat.update({ status: constants_1.default.chat_statuses.rejected });
// dang.. nothing really to do here? // dang.. nothing really to do here?
let date = new Date(); let date = new Date();
date.setMilliseconds(0); date.setMilliseconds(0);
const msg = { const msg = {
chatId: chat.id, chatId: chat.id,
type: constants.message_types.member_reject, type: constants_1.default.message_types.member_reject,
sender: (sender && sender.id) || 0, sender: (sender && sender.id) || 0,
messageContent: '', remoteMessageContent: '', messageContent: '', remoteMessageContent: '',
status: constants.statuses.confirmed, status: constants_1.default.statuses.confirmed,
date: date, createdAt: date, updatedAt: date date: date, createdAt: date, updatedAt: date
}; };
const message = yield models_1.models.Message.create(msg); const message = yield models_1.models.Message.create(msg);
@ -395,10 +394,10 @@ function receiveTribeDelete(payload) {
date.setMilliseconds(0); date.setMilliseconds(0);
const msg = { const msg = {
chatId: chat.id, chatId: chat.id,
type: constants.message_types.tribe_delete, type: constants_1.default.message_types.tribe_delete,
sender: (sender && sender.id) || 0, sender: (sender && sender.id) || 0,
messageContent: '', remoteMessageContent: '', messageContent: '', remoteMessageContent: '',
status: constants.statuses.confirmed, status: constants_1.default.statuses.confirmed,
date: date, createdAt: date, updatedAt: date date: date, createdAt: date, updatedAt: date
}; };
const message = yield models_1.models.Message.create(msg); const message = yield models_1.models.Message.create(msg);
@ -429,7 +428,7 @@ function replayChatHistory(chat, contact) {
asyncForEach(msgs, (m) => __awaiter(this, void 0, void 0, function* () { asyncForEach(msgs, (m) => __awaiter(this, void 0, void 0, function* () {
if (!network.typesToReplay.includes(m.type)) if (!network.typesToReplay.includes(m.type))
return; // only for message for now return; // only for message for now
const sender = Object.assign(Object.assign(Object.assign({}, owner.dataValues), m.senderAlias && { alias: m.senderAlias }), { role: constants.chat_roles.reader }); const sender = Object.assign(Object.assign(Object.assign({}, owner.dataValues), m.senderAlias && { alias: m.senderAlias }), { role: constants_1.default.chat_roles.reader });
let content = ''; let content = '';
try { try {
content = JSON.parse(m.remoteMessageContent); content = JSON.parse(m.remoteMessageContent);
@ -438,7 +437,7 @@ function replayChatHistory(chat, contact) {
const dateString = m.date && m.date.toISOString(); const dateString = m.date && m.date.toISOString();
let mediaKeyMap; let mediaKeyMap;
let newMediaTerms; let newMediaTerms;
if (m.type === constants.message_types.attachment) { if (m.type === constants_1.default.message_types.attachment) {
if (m.mediaKey && m.mediaToken) { if (m.mediaKey && m.mediaToken) {
const muid = m.mediaToken.split('.').length && m.mediaToken.split('.')[1]; const muid = m.mediaToken.split('.').length && m.mediaToken.split('.')[1];
if (muid) { if (muid) {
@ -488,7 +487,7 @@ function createTribeChatParams(owner, contactIds, name, img, price_per_message,
updatedAt: date, updatedAt: date,
photoUrl: img || '', photoUrl: img || '',
name: name, name: name,
type: constants.chat_types.tribe, type: constants_1.default.chat_types.tribe,
groupKey: keys.public, groupKey: keys.public,
groupPrivateKey: keys.private, groupPrivateKey: keys.private,
host: tribes.getHost(), host: tribes.getHost(),
@ -507,7 +506,7 @@ function addPendingContactIdsToChat(achat) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const members = yield models_1.models.ChatMember.findAll({ where: { const members = yield models_1.models.ChatMember.findAll({ where: {
chatId: achat.id, chatId: achat.id,
status: constants.chat_statuses.pending // only pending status: constants_1.default.chat_statuses.pending // only pending
} }); } });
if (!members) if (!members)
return achat; return achat;

2
dist/src/controllers/chatTribes.js.map

File diff suppressed because one or more lines are too long

67
dist/src/controllers/chats.js

@ -17,11 +17,10 @@ const network = require("../network");
const socket = require("../utils/socket"); const socket = require("../utils/socket");
const hub_1 = require("../hub"); const hub_1 = require("../hub");
const md5 = require("md5"); const md5 = require("md5");
const path = require("path");
const tribes = require("../utils/tribes"); const tribes = require("../utils/tribes");
const timers = require("../utils/timers"); const timers = require("../utils/timers");
const chatTribes_1 = require("./chatTribes"); const chatTribes_1 = require("./chatTribes");
const constants = require(path.join(__dirname, '../../config/constants.json')); const constants_1 = require("../constants");
function updateChat(req, res) { function updateChat(req, res) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
console.log('=> updateChat'); console.log('=> updateChat');
@ -67,7 +66,7 @@ function kickChatMember(req, res) {
chat: Object.assign(Object.assign({}, chat.dataValues), { contactIds: [contactId] }), chat: Object.assign(Object.assign({}, chat.dataValues), { contactIds: [contactId] }),
sender: owner, sender: owner,
message: {}, message: {},
type: constants.message_types.group_kick, type: constants_1.default.message_types.group_kick,
}); });
// delete all timers for this member // delete all timers for this member
timers.removeTimersByContactIdChatId(contactId, chatId); timers.removeTimersByContactIdChatId(contactId, chatId);
@ -98,10 +97,10 @@ function receiveGroupKick(payload) {
date = new Date(date_string); date = new Date(date_string);
const msg = { const msg = {
chatId: chat.id, chatId: chat.id,
type: constants.message_types.group_kick, type: constants_1.default.message_types.group_kick,
sender: (sender && sender.id) || 0, sender: (sender && sender.id) || 0,
messageContent: '', remoteMessageContent: '', messageContent: '', remoteMessageContent: '',
status: constants.statuses.confirmed, status: constants_1.default.statuses.confirmed,
date: date, createdAt: date, updatedAt: date, date: date, createdAt: date, updatedAt: date,
}; };
const message = yield models_1.models.Message.create(msg); const message = yield models_1.models.Message.create(msg);
@ -187,7 +186,7 @@ function createGroupChat(req, res) {
} }
} }
// make me owner when i create // make me owner when i create
members[owner.publicKey].role = constants.chat_roles.owner; members[owner.publicKey].role = constants_1.default.chat_roles.owner;
} }
else { else {
chatParams = createGroupChatParams(owner, contact_ids, members, name); chatParams = createGroupChatParams(owner, contact_ids, members, name);
@ -198,7 +197,7 @@ function createGroupChat(req, res) {
network.sendMessage({ network.sendMessage({
chat: Object.assign(Object.assign({}, chatParams), { members }), chat: Object.assign(Object.assign({}, chatParams), { members }),
sender: owner, sender: owner,
type: constants.message_types.group_create, type: constants_1.default.message_types.group_create,
message: {}, message: {},
failure: function (e) { failure: function (e) {
res_1.failure(res, e); res_1.failure(res, e);
@ -206,12 +205,12 @@ function createGroupChat(req, res) {
success: function () { success: function () {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const chat = yield models_1.models.Chat.create(chatParams); const chat = yield models_1.models.Chat.create(chatParams);
if (chat.type === constants.chat_types.tribe) { // save me as owner when i create if (chat.type === constants_1.default.chat_types.tribe) { // save me as owner when i create
yield models_1.models.ChatMember.create({ yield models_1.models.ChatMember.create({
contactId: owner.id, contactId: owner.id,
chatId: chat.id, chatId: chat.id,
role: constants.chat_roles.owner, role: constants_1.default.chat_roles.owner,
status: constants.chat_statuses.approved status: constants_1.default.chat_statuses.approved
}); });
} }
res_1.success(res, jsonUtils.chatToJson(chat)); res_1.success(res, jsonUtils.chatToJson(chat));
@ -232,7 +231,7 @@ function addGroupMembers(req, res) {
const contactIds = JSON.parse(chat.contactIds || '[]'); const contactIds = JSON.parse(chat.contactIds || '[]');
// for all members (existing and new) // for all members (existing and new)
members[owner.publicKey] = { key: owner.contactKey, alias: owner.alias }; members[owner.publicKey] = { key: owner.contactKey, alias: owner.alias };
if (chat.type === constants.chat_types.tribe) { if (chat.type === constants_1.default.chat_types.tribe) {
const me = yield models_1.models.ChatMember.findOne({ where: { contactId: owner.id, chatId: chat.id } }); const me = yield models_1.models.ChatMember.findOne({ where: { contactId: owner.id, chatId: chat.id } });
if (me) if (me)
members[owner.publicKey].role = me.role; members[owner.publicKey].role = me.role;
@ -254,7 +253,7 @@ function addGroupMembers(req, res) {
network.sendMessage({ network.sendMessage({
chat: Object.assign(Object.assign({}, chat.dataValues), { contactIds: contact_ids, members }), chat: Object.assign(Object.assign({}, chat.dataValues), { contactIds: contact_ids, members }),
sender: owner, sender: owner,
type: constants.message_types.group_invite, type: constants_1.default.message_types.group_invite,
message: {} message: {}
}); });
}); });
@ -275,7 +274,7 @@ exports.deleteChat = (req, res) => __awaiter(void 0, void 0, void 0, function* (
chat, chat,
sender: owner, sender: owner,
message: {}, message: {},
type: constants.message_types.tribe_delete, type: constants_1.default.message_types.tribe_delete,
success: function () { success: function () {
tribes.delete_tribe(chat.uuid); tribes.delete_tribe(chat.uuid);
}, },
@ -289,14 +288,14 @@ exports.deleteChat = (req, res) => __awaiter(void 0, void 0, void 0, function* (
} }
else { else {
// leave a group or tribe // leave a group or tribe
const isPending = chat.status === constants.chat_statuses.pending; const isPending = chat.status === constants_1.default.chat_statuses.pending;
const isRejected = chat.status === constants.chat_statuses.rejected; const isRejected = chat.status === constants_1.default.chat_statuses.rejected;
if (!isPending && !isRejected) { // dont send if pending if (!isPending && !isRejected) { // dont send if pending
network.sendMessage({ network.sendMessage({
chat, chat,
sender: owner, sender: owner,
message: {}, message: {},
type: constants.message_types.group_leave, type: constants_1.default.message_types.group_leave,
}); });
} }
} }
@ -320,7 +319,7 @@ function receiveGroupJoin(payload) {
const chat = yield models_1.models.Chat.findOne({ where: { uuid: chat_uuid } }); const chat = yield models_1.models.Chat.findOne({ where: { uuid: chat_uuid } });
if (!chat) if (!chat)
return; return;
const isTribe = chat_type === constants.chat_types.tribe; const isTribe = chat_type === constants_1.default.chat_types.tribe;
var date = new Date(); var date = new Date();
date.setMilliseconds(0); date.setMilliseconds(0);
if (date_string) if (date_string)
@ -363,9 +362,9 @@ function receiveGroupJoin(payload) {
models_1.models.ChatMember.upsert({ models_1.models.ChatMember.upsert({
contactId: theSender.id, contactId: theSender.id,
chatId: chat.id, chatId: chat.id,
role: constants.chat_roles.reader, role: constants_1.default.chat_roles.reader,
lastActive: date, lastActive: date,
status: constants.chat_statuses.approved status: constants_1.default.chat_statuses.approved
}); });
} }
catch (e) { } catch (e) { }
@ -380,10 +379,10 @@ function receiveGroupJoin(payload) {
} }
const msg = { const msg = {
chatId: chat.id, chatId: chat.id,
type: constants.message_types.group_join, type: constants_1.default.message_types.group_join,
sender: (theSender && theSender.id) || 0, sender: (theSender && theSender.id) || 0,
messageContent: '', remoteMessageContent: '', messageContent: '', remoteMessageContent: '',
status: constants.statuses.confirmed, status: constants_1.default.statuses.confirmed,
date: date, createdAt: date, updatedAt: date date: date, createdAt: date, updatedAt: date
}; };
if (isTribe) { if (isTribe) {
@ -409,7 +408,7 @@ function receiveGroupLeave(payload) {
const chat = yield models_1.models.Chat.findOne({ where: { uuid: chat_uuid } }); const chat = yield models_1.models.Chat.findOne({ where: { uuid: chat_uuid } });
if (!chat) if (!chat)
return; return;
const isTribe = chat_type === constants.chat_types.tribe; const isTribe = chat_type === constants_1.default.chat_types.tribe;
let sender; let sender;
// EITHER private chat OR tribeOwner // EITHER private chat OR tribeOwner
if (!isTribe || isTribeOwner) { if (!isTribe || isTribeOwner) {
@ -420,7 +419,7 @@ function receiveGroupLeave(payload) {
const contactIds = oldContactIds.filter(cid => cid !== sender.id); const contactIds = oldContactIds.filter(cid => cid !== sender.id);
yield chat.update({ contactIds: JSON.stringify(contactIds) }); yield chat.update({ contactIds: JSON.stringify(contactIds) });
if (isTribeOwner) { if (isTribeOwner) {
if (chat_type === constants.chat_types.tribe) { if (chat_type === constants_1.default.chat_types.tribe) {
try { try {
yield models_1.models.ChatMember.destroy({ where: { chatId: chat.id, contactId: sender.id } }); yield models_1.models.ChatMember.destroy({ where: { chatId: chat.id, contactId: sender.id } });
} }
@ -440,10 +439,10 @@ function receiveGroupLeave(payload) {
date = new Date(date_string); date = new Date(date_string);
const msg = { const msg = {
chatId: chat.id, chatId: chat.id,
type: constants.message_types.group_leave, type: constants_1.default.message_types.group_leave,
sender: (sender && sender.id) || 0, sender: (sender && sender.id) || 0,
messageContent: '', remoteMessageContent: '', messageContent: '', remoteMessageContent: '',
status: constants.statuses.confirmed, status: constants_1.default.statuses.confirmed,
date: date, createdAt: date, updatedAt: date date: date, createdAt: date, updatedAt: date
}; };
if (isTribe) { if (isTribe) {
@ -474,7 +473,7 @@ function receiveGroupCreateOrInvite(payload) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const { sender_pub_key, chat_members, chat_name, chat_uuid, chat_type, chat_host, chat_key } = yield helpers.parseReceiveParams(payload); const { sender_pub_key, chat_members, chat_name, chat_uuid, chat_type, chat_host, chat_key } = yield helpers.parseReceiveParams(payload);
// maybe this just needs to move to adding tribe owner ChatMember? // maybe this just needs to move to adding tribe owner ChatMember?
const isTribe = chat_type === constants.chat_types.tribe; const isTribe = chat_type === constants_1.default.chat_types.tribe;
if (isTribe) { // must be sent by tribe owner????? if (isTribe) { // must be sent by tribe owner?????
const validOwner = yield validateTribeOwner(chat_uuid, sender_pub_key); const validOwner = yield validateTribeOwner(chat_uuid, sender_pub_key);
if (!validOwner) if (!validOwner)
@ -485,11 +484,11 @@ function receiveGroupCreateOrInvite(payload) {
for (let [pubkey, member] of Object.entries(chat_members)) { for (let [pubkey, member] of Object.entries(chat_members)) {
const contact = yield models_1.models.Contact.findOne({ where: { publicKey: pubkey } }); const contact = yield models_1.models.Contact.findOne({ where: { publicKey: pubkey } });
let addContact = false; let addContact = false;
if (chat_type === constants.chat_types.group && member && member.key) { if (chat_type === constants_1.default.chat_types.group && member && member.key) {
addContact = true; addContact = true;
} }
else if (isTribe && member && member.role) { else if (isTribe && member && member.role) {
if (member.role === constants.chat_roles.owner || member.role === constants.chat_roles.admin || member.role === constants.chat_roles.mod) { if (member.role === constants_1.default.chat_roles.owner || member.role === constants_1.default.chat_roles.admin || member.role === constants_1.default.chat_roles.mod) {
addContact = true; addContact = true;
} }
} }
@ -517,15 +516,15 @@ function receiveGroupCreateOrInvite(payload) {
// make chat // make chat
let date = new Date(); let date = new Date();
date.setMilliseconds(0); date.setMilliseconds(0);
const chat = yield models_1.models.Chat.create(Object.assign(Object.assign({ uuid: chat_uuid, contactIds: JSON.stringify(contactIds), createdAt: date, updatedAt: date, name: chat_name, type: chat_type || constants.chat_types.group }, chat_host && { host: chat_host }), chat_key && { groupKey: chat_key })); const chat = yield models_1.models.Chat.create(Object.assign(Object.assign({ uuid: chat_uuid, contactIds: JSON.stringify(contactIds), createdAt: date, updatedAt: date, name: chat_name, type: chat_type || constants_1.default.chat_types.group }, chat_host && { host: chat_host }), chat_key && { groupKey: chat_key }));
if (isTribe) { // IF TRIBE, ADD TO XREF if (isTribe) { // IF TRIBE, ADD TO XREF
contacts.forEach(c => { contacts.forEach(c => {
models_1.models.ChatMember.create({ models_1.models.ChatMember.create({
contactId: c.id, contactId: c.id,
chatId: chat.id, chatId: chat.id,
role: c.role || constants.chat_roles.reader, role: c.role || constants_1.default.chat_roles.reader,
lastActive: date, lastActive: date,
status: constants.chat_statuses.approved status: constants_1.default.chat_statuses.approved
}); });
}); });
} }
@ -534,7 +533,7 @@ function receiveGroupCreateOrInvite(payload) {
response: jsonUtils.messageToJson({ newContacts }, chat) response: jsonUtils.messageToJson({ newContacts }, chat)
}); });
hub_1.sendNotification(chat, chat_name, 'group'); hub_1.sendNotification(chat, chat_name, 'group');
if (payload.type === constants.message_types.group_invite) { if (payload.type === constants_1.default.message_types.group_invite) {
const owner = yield models_1.models.Contact.findOne({ where: { isOwner: true } }); const owner = yield models_1.models.Contact.findOne({ where: { isOwner: true } });
network.sendMessage({ network.sendMessage({
chat: Object.assign(Object.assign({}, chat.dataValues), { members: { chat: Object.assign(Object.assign({}, chat.dataValues), { members: {
@ -545,7 +544,7 @@ function receiveGroupCreateOrInvite(payload) {
} }), } }),
sender: owner, sender: owner,
message: {}, message: {},
type: constants.message_types.group_join, type: constants_1.default.message_types.group_join,
}); });
} }
}); });
@ -572,7 +571,7 @@ function createGroupChatParams(owner, contactIds, members, name) {
createdAt: date, createdAt: date,
updatedAt: date, updatedAt: date,
name: name, name: name,
type: constants.chat_types.group type: constants_1.default.chat_types.group
}; };
} }
function asyncForEach(array, callback) { function asyncForEach(array, callback) {

2
dist/src/controllers/chats.js.map

File diff suppressed because one or more lines are too long

28
dist/src/controllers/confirmations.js

@ -14,8 +14,7 @@ const models_1 = require("../models");
const socket = require("../utils/socket"); const socket = require("../utils/socket");
const jsonUtils = require("../utils/json"); const jsonUtils = require("../utils/json");
const network = require("../network"); const network = require("../network");
const path = require("path"); const constants_1 = require("../constants");
const constants = require(path.join(__dirname, '../../config/constants.json'));
function sendConfirmation({ chat, sender, msg_id }) { function sendConfirmation({ chat, sender, msg_id }) {
if (!msg_id) if (!msg_id)
return; return;
@ -23,7 +22,7 @@ function sendConfirmation({ chat, sender, msg_id }) {
chat, chat,
sender, sender,
message: { id: msg_id }, message: { id: msg_id },
type: constants.message_types.confirmation, type: constants_1.default.message_types.confirmation,
}); });
} }
exports.sendConfirmation = sendConfirmation; exports.sendConfirmation = sendConfirmation;
@ -49,9 +48,9 @@ function receiveConfirmation(payload) {
statusMap = JSON.parse(message.statusMap || '{}'); statusMap = JSON.parse(message.statusMap || '{}');
} }
catch (e) { } catch (e) { }
statusMap[sender.id] = constants.statuses.received; statusMap[sender.id] = constants_1.default.statuses.received;
yield message.update({ yield message.update({
status: constants.statuses.received, status: constants_1.default.statuses.received,
statusMap: JSON.stringify(statusMap) statusMap: JSON.stringify(statusMap)
}); });
socket.sendJson({ socket.sendJson({
@ -70,16 +69,16 @@ function receiveConfirmation(payload) {
chatId: chat.id, chatId: chat.id,
sender: owner.id, sender: owner.id,
type: [ type: [
constants.message_types.message, constants_1.default.message_types.message,
constants.message_types.invoice, constants_1.default.message_types.invoice,
constants.message_types.attachment, constants_1.default.message_types.attachment,
], ],
status: constants.statuses.pending, status: constants_1.default.statuses.pending,
}, },
order: [['createdAt', 'desc']] order: [['createdAt', 'desc']]
}); });
const message = messages[0]; const message = messages[0];
message.update({ status: constants.statuses.received }); message.update({ status: constants_1.default.statuses.received });
socket.sendJson({ socket.sendJson({
type: 'confirmation', type: 'confirmation',
response: jsonUtils.messageToJson(message, chat, sender) response: jsonUtils.messageToJson(message, chat, sender)
@ -100,9 +99,9 @@ function tribeOwnerAutoConfirmation(msg_id, chat_uuid) {
statusMap = JSON.parse(message.statusMap || '{}'); statusMap = JSON.parse(message.statusMap || '{}');
} }
catch (e) { } catch (e) { }
statusMap['chat'] = constants.statuses.received; statusMap['chat'] = constants_1.default.statuses.received;
yield message.update({ yield message.update({
status: constants.statuses.received, status: constants_1.default.statuses.received,
statusMap: JSON.stringify(statusMap) statusMap: JSON.stringify(statusMap)
}); });
socket.sendJson({ socket.sendJson({
@ -125,13 +124,12 @@ function receiveHeartbeat(payload) {
return console.log('no amount'); return console.log('no amount');
const owner = yield models_1.models.Contact.findOne({ where: { isOwner: true } }); const owner = yield models_1.models.Contact.findOne({ where: { isOwner: true } });
const amount = Math.round(receivedAmount / 2); const amount = Math.round(receivedAmount / 2);
const MIN_SATS = 3; const amt = Math.max(amount || constants_1.default.min_sat_amount);
const amt = Math.max(amount || MIN_SATS);
const opts = { const opts = {
amt, amt,
dest: sender_pub_key, dest: sender_pub_key,
data: { data: {
type: constants.message_types.heartbeat_confirmation, type: constants_1.default.message_types.heartbeat_confirmation,
message: { amount: amt }, message: { amount: amt },
sender: { pub_key: owner.publicKey } sender: { pub_key: owner.publicKey }
} }

2
dist/src/controllers/confirmations.js.map

@ -1 +1 @@
{"version":3,"file":"confirmations.js","sourceRoot":"","sources":["../../../src/controllers/confirmations.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,wCAAgC;AAChC,sCAAkC;AAClC,0CAAyC;AACzC,2CAA0C;AAC1C,sCAAqC;AACrC,6BAA4B;AAE5B,MAAM,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,6BAA6B,CAAC,CAAC,CAAA;AAE9E,SAAgB,gBAAgB,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE;IACxD,IAAI,CAAC,MAAM;QAAE,OAAM;IACnB,OAAO,CAAC,WAAW,CAAC;QACnB,IAAI;QACJ,MAAM;QACN,OAAO,EAAE,EAAE,EAAE,EAAE,MAAM,EAAE;QACvB,IAAI,EAAE,SAAS,CAAC,aAAa,CAAC,YAAY;KAC1C,CAAC,CAAA;AACH,CAAC;AARD,4CAQC;AAED,SAAsB,mBAAmB,CAAC,OAAO;;QAChD,OAAO,CAAC,GAAG,CAAC,0BAA0B,EAAE,CAAC,OAAO,CAAC,OAAO,IAAI,OAA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CA6BC"}

19
dist/src/controllers/contacts.js

@ -16,16 +16,15 @@ const helpers = require("../helpers");
const jsonUtils = require("../utils/json"); const jsonUtils = require("../utils/json");
const res_1 = require("../utils/res"); const res_1 = require("../utils/res");
const password_1 = require("../utils/password"); const password_1 = require("../utils/password");
const path = require("path");
const sequelize_1 = require("sequelize"); const sequelize_1 = require("sequelize");
const constants = require(path.join(__dirname, '../../config/constants.json')); const constants_1 = require("../constants");
exports.getContacts = (req, res) => __awaiter(void 0, void 0, void 0, function* () { exports.getContacts = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
const contacts = yield models_1.models.Contact.findAll({ where: { deleted: false }, raw: true }); const contacts = yield models_1.models.Contact.findAll({ where: { deleted: false }, raw: true });
const invites = yield models_1.models.Invite.findAll({ raw: true }); const invites = yield models_1.models.Invite.findAll({ raw: true });
const chats = yield models_1.models.Chat.findAll({ where: { deleted: false }, raw: true }); const chats = yield models_1.models.Chat.findAll({ where: { deleted: false }, raw: true });
const subscriptions = yield models_1.models.Subscription.findAll({ raw: true }); const subscriptions = yield models_1.models.Subscription.findAll({ raw: true });
const pendingMembers = yield models_1.models.ChatMember.findAll({ where: { const pendingMembers = yield models_1.models.ChatMember.findAll({ where: {
status: constants.chat_statuses.pending status: constants_1.default.chat_statuses.pending
} }); } });
const contactsResponse = contacts.map(contact => { const contactsResponse = contacts.map(contact => {
let contactJson = jsonUtils.contactToJson(contact); let contactJson = jsonUtils.contactToJson(contact);
@ -98,7 +97,7 @@ exports.updateContact = (req, res) => __awaiter(void 0, void 0, void 0, function
helpers.sendContactKeys({ helpers.sendContactKeys({
contactIds: contactIds, contactIds: contactIds,
sender: owner, sender: owner,
type: constants.message_types.contact_key, type: constants_1.default.message_types.contact_key,
}); });
}); });
exports.exchangeKeys = (req, res) => __awaiter(void 0, void 0, void 0, function* () { exports.exchangeKeys = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
@ -109,7 +108,7 @@ exports.exchangeKeys = (req, res) => __awaiter(void 0, void 0, void 0, function*
helpers.sendContactKeys({ helpers.sendContactKeys({
contactIds: [contact.id], contactIds: [contact.id],
sender: owner, sender: owner,
type: constants.message_types.contact_key, type: constants_1.default.message_types.contact_key,
}); });
}); });
exports.createContact = (req, res) => __awaiter(void 0, void 0, void 0, function* () { exports.createContact = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
@ -132,7 +131,7 @@ exports.createContact = (req, res) => __awaiter(void 0, void 0, void 0, function
helpers.sendContactKeys({ helpers.sendContactKeys({
contactIds: [contact.id], contactIds: [contact.id],
sender: owner, sender: owner,
type: constants.message_types.contact_key, type: constants_1.default.message_types.contact_key,
}); });
}); });
exports.deleteContact = (req, res) => __awaiter(void 0, void 0, void 0, function* () { exports.deleteContact = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
@ -168,7 +167,7 @@ exports.deleteContact = (req, res) => __awaiter(void 0, void 0, void 0, function
// find and destroy chat & messages // find and destroy chat & messages
const chats = yield models_1.models.Chat.findAll({ where: { deleted: false } }); const chats = yield models_1.models.Chat.findAll({ where: { deleted: false } });
chats.map((chat) => __awaiter(void 0, void 0, void 0, function* () { chats.map((chat) => __awaiter(void 0, void 0, void 0, function* () {
if (chat.type === constants.chat_types.conversation) { if (chat.type === constants_1.default.chat_types.conversation) {
const contactIds = JSON.parse(chat.contactIds); const contactIds = JSON.parse(chat.contactIds);
if (contactIds.includes(id)) { if (contactIds.includes(id)) {
yield chat.update({ yield chat.update({
@ -196,7 +195,7 @@ exports.receiveContactKey = (payload) => __awaiter(void 0, void 0, void 0, funct
return console.log("no pubkey!"); return console.log("no pubkey!");
} }
const owner = yield models_1.models.Contact.findOne({ where: { isOwner: true } }); const owner = yield models_1.models.Contact.findOne({ where: { isOwner: true } });
const sender = yield models_1.models.Contact.findOne({ where: { publicKey: sender_pub_key, status: constants.contact_statuses.confirmed } }); const sender = yield models_1.models.Contact.findOne({ where: { publicKey: sender_pub_key, status: constants_1.default.contact_statuses.confirmed } });
if (sender_contact_key && sender) { if (sender_contact_key && sender) {
const objToUpdate = { contactKey: sender_contact_key }; const objToUpdate = { contactKey: sender_contact_key };
if (sender_alias) if (sender_alias)
@ -215,7 +214,7 @@ exports.receiveContactKey = (payload) => __awaiter(void 0, void 0, void 0, funct
helpers.sendContactKeys({ helpers.sendContactKeys({
contactPubKey: sender_pub_key, contactPubKey: sender_pub_key,
sender: owner, sender: owner,
type: constants.message_types.contact_key_confirmation, type: constants_1.default.message_types.contact_key_confirmation,
}); });
}); });
exports.receiveConfirmContactKey = (payload) => __awaiter(void 0, void 0, void 0, function* () { exports.receiveConfirmContactKey = (payload) => __awaiter(void 0, void 0, void 0, function* () {
@ -228,7 +227,7 @@ exports.receiveConfirmContactKey = (payload) => __awaiter(void 0, void 0, void 0
if (!sender_pub_key) { if (!sender_pub_key) {
return console.log("no pubkey!"); return console.log("no pubkey!");
} }
const sender = yield models_1.models.Contact.findOne({ where: { publicKey: sender_pub_key, status: constants.contact_statuses.confirmed } }); const sender = yield models_1.models.Contact.findOne({ where: { publicKey: sender_pub_key, status: constants_1.default.contact_statuses.confirmed } });
if (sender_contact_key && sender) { if (sender_contact_key && sender) {
const objToUpdate = { contactKey: sender_contact_key }; const objToUpdate = { contactKey: sender_contact_key };
if (sender_alias) if (sender_alias)

2
dist/src/controllers/contacts.js.map

File diff suppressed because one or more lines are too long

5
dist/src/controllers/index.js

@ -25,12 +25,11 @@ const uploads = require("./uploads");
const confirmations = require("./confirmations"); const confirmations = require("./confirmations");
const actions = require("./api"); const actions = require("./api");
const gitinfo_1 = require("../utils/gitinfo"); const gitinfo_1 = require("../utils/gitinfo");
const path = require("path");
const timers = require("../utils/timers"); const timers = require("../utils/timers");
const builtInBots = require("../builtin"); const builtInBots = require("../builtin");
const constants_1 = require("../constants");
const env = process.env.NODE_ENV || 'development'; const env = process.env.NODE_ENV || 'development';
console.log("=> env:", env); console.log("=> env:", env);
const constants = require(path.join(__dirname, '../../config/constants.json'));
function set(app) { function set(app) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
builtInBots.init(); builtInBots.init();
@ -121,7 +120,7 @@ function set(app) {
}); });
} }
exports.set = set; exports.set = set;
const msgtypes = constants.message_types; const msgtypes = constants_1.default.message_types;
exports.ACTIONS = { exports.ACTIONS = {
[msgtypes.contact_key]: contacts.receiveContactKey, [msgtypes.contact_key]: contacts.receiveContactKey,
[msgtypes.contact_key_confirmation]: contacts.receiveConfirmContactKey, [msgtypes.contact_key_confirmation]: contacts.receiveConfirmContactKey,

2
dist/src/controllers/index.js.map

File diff suppressed because one or more lines are too long

21
dist/src/controllers/invoices.js

@ -18,10 +18,9 @@ const helpers = require("../helpers");
const hub_1 = require("../hub"); const hub_1 = require("../hub");
const res_1 = require("../utils/res"); const res_1 = require("../utils/res");
const confirmations_1 = require("./confirmations"); const confirmations_1 = require("./confirmations");
const path = require("path");
const network = require("../network"); const network = require("../network");
const short = require("short-uuid"); const short = require("short-uuid");
const constants = require(path.join(__dirname, '../../config/constants.json')); const constants_1 = require("../constants");
function stripLightningPrefix(s) { function stripLightningPrefix(s) {
if (s.toLowerCase().startsWith('lightning:')) if (s.toLowerCase().startsWith('lightning:'))
return s.substring(10); return s.substring(10);
@ -48,7 +47,7 @@ exports.payInvoice = (req, res) => __awaiter(void 0, void 0, void 0, function* (
response: { payment_request } response: { payment_request }
}); });
} }
message.status = constants.statuses.confirmed; message.status = constants_1.default.statuses.confirmed;
message.save(); message.save();
var date = new Date(); var date = new Date();
date.setMilliseconds(0); date.setMilliseconds(0);
@ -58,14 +57,14 @@ exports.payInvoice = (req, res) => __awaiter(void 0, void 0, void 0, function* (
const paidMessage = yield models_1.models.Message.create({ const paidMessage = yield models_1.models.Message.create({
chatId: message.chatId, chatId: message.chatId,
sender: senderId, sender: senderId,
type: constants.message_types.payment, type: constants_1.default.message_types.payment,
amount: message.amount, amount: message.amount,
amountMsat: message.amountMsat, amountMsat: message.amountMsat,
paymentHash: message.paymentHash, paymentHash: message.paymentHash,
date: date, date: date,
expirationDate: null, expirationDate: null,
messageContent: null, messageContent: null,
status: constants.statuses.confirmed, status: constants_1.default.statuses.confirmed,
createdAt: date, createdAt: date,
updatedAt: date updatedAt: date
}); });
@ -125,7 +124,7 @@ exports.createInvoice = (req, res) => __awaiter(void 0, void 0, void 0, function
chatId: chat.id, chatId: chat.id,
uuid: short.generate(), uuid: short.generate(),
sender: owner.id, sender: owner.id,
type: constants.message_types.invoice, type: constants_1.default.message_types.invoice,
amount: parseInt(invoice.num_satoshis), amount: parseInt(invoice.num_satoshis),
amountMsat: parseInt(invoice.num_satoshis) * 1000, amountMsat: parseInt(invoice.num_satoshis) * 1000,
paymentHash: invoice.payment_hash, paymentHash: invoice.payment_hash,
@ -134,7 +133,7 @@ exports.createInvoice = (req, res) => __awaiter(void 0, void 0, void 0, function
expirationDate: new Date(timestamp + expiry), expirationDate: new Date(timestamp + expiry),
messageContent: memo, messageContent: memo,
remoteMessageContent: remote_memo, remoteMessageContent: remote_memo,
status: constants.statuses.pending, status: constants_1.default.statuses.pending,
createdAt: new Date(timestamp), createdAt: new Date(timestamp),
updatedAt: new Date(timestamp) updatedAt: new Date(timestamp)
}); });
@ -142,7 +141,7 @@ exports.createInvoice = (req, res) => __awaiter(void 0, void 0, void 0, function
network.sendMessage({ network.sendMessage({
chat: chat, chat: chat,
sender: owner, sender: owner,
type: constants.message_types.invoice, type: constants_1.default.message_types.invoice,
message: { message: {
id: message.id, id: message.id,
invoice: message.paymentRequest invoice: message.paymentRequest
@ -193,7 +192,7 @@ exports.receiveInvoice = (payload) => __awaiter(void 0, void 0, void 0, function
const msg = { const msg = {
chatId: chat.id, chatId: chat.id,
uuid: msg_uuid, uuid: msg_uuid,
type: constants.message_types.invoice, type: constants_1.default.message_types.invoice,
sender: sender.id, sender: sender.id,
amount: sat, amount: sat,
amountMsat: msat, amountMsat: msat,
@ -203,11 +202,11 @@ exports.receiveInvoice = (payload) => __awaiter(void 0, void 0, void 0, function
messageContent: memo, messageContent: memo,
expirationDate: new Date(invoiceDate + expirationSeconds), expirationDate: new Date(invoiceDate + expirationSeconds),
date: new Date(invoiceDate), date: new Date(invoiceDate),
status: constants.statuses.pending, status: constants_1.default.statuses.pending,
createdAt: date, createdAt: date,
updatedAt: date updatedAt: date
}; };
const isTribe = chat_type === constants.chat_types.tribe; const isTribe = chat_type === constants_1.default.chat_types.tribe;
if (isTribe) { if (isTribe) {
msg.senderAlias = sender_alias; msg.senderAlias = sender_alias;
} }

2
dist/src/controllers/invoices.js.map

File diff suppressed because one or more lines are too long

36
dist/src/controllers/media.js

@ -27,9 +27,9 @@ const path = require("path");
const network = require("../network"); const network = require("../network");
const meme = require("../utils/meme"); const meme = require("../utils/meme");
const short = require("short-uuid"); const short = require("short-uuid");
const constants_1 = require("../constants");
const env = process.env.NODE_ENV || 'development'; const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname, '../../config/app.json'))[env]; const config = require(path.join(__dirname, '../../config/app.json'))[env];
const constants = require(path.join(__dirname, '../../config/constants.json'));
/* /*
TODO line 233: parse that from token itself, dont use getMediaInfo at all TODO line 233: parse that from token itself, dont use getMediaInfo at all
@ -85,8 +85,8 @@ exports.sendAttachmentMessage = (req, res) => __awaiter(void 0, void 0, void 0,
chatId: chat.id, chatId: chat.id,
uuid: uuid, uuid: uuid,
sender: owner.id, sender: owner.id,
type: constants.message_types.attachment, type: constants_1.default.message_types.attachment,
status: constants.statuses.pending, status: constants_1.default.statuses.pending,
amount: amount || 0, amount: amount || 0,
messageContent: text || file_name || '', messageContent: text || file_name || '',
remoteMessageContent, remoteMessageContent,
@ -120,7 +120,7 @@ exports.sendAttachmentMessage = (req, res) => __awaiter(void 0, void 0, void 0,
network.sendMessage({ network.sendMessage({
chat: chat, chat: chat,
sender: owner, sender: owner,
type: constants.message_types.attachment, type: constants_1.default.message_types.attachment,
amount: amount || 0, amount: amount || 0,
message: msg, message: msg,
success: (data) => __awaiter(void 0, void 0, void 0, function* () { success: (data) => __awaiter(void 0, void 0, void 0, function* () {
@ -170,7 +170,7 @@ exports.purchase = (req, res) => __awaiter(void 0, void 0, void 0, function* ()
chatId: chat.id, chatId: chat.id,
uuid: short.generate(), uuid: short.generate(),
sender: owner.id, sender: owner.id,
type: constants.message_types.purchase, type: constants_1.default.message_types.purchase,
amount: amount || 0, amount: amount || 0,
mediaToken: media_token, mediaToken: media_token,
date: date, date: date,
@ -184,7 +184,7 @@ exports.purchase = (req, res) => __awaiter(void 0, void 0, void 0, function* ()
network.sendMessage({ network.sendMessage({
chat: Object.assign(Object.assign({}, chat.dataValues), { contactIds: [contact_id] }), chat: Object.assign(Object.assign({}, chat.dataValues), { contactIds: [contact_id] }),
sender: owner, sender: owner,
type: constants.message_types.purchase, type: constants_1.default.message_types.purchase,
message: msg, message: msg,
amount: amount, amount: amount,
success: (data) => __awaiter(void 0, void 0, void 0, function* () { success: (data) => __awaiter(void 0, void 0, void 0, function* () {
@ -207,7 +207,7 @@ exports.receivePurchase = (payload) => __awaiter(void 0, void 0, void 0, functio
chatId: chat.id, chatId: chat.id,
uuid: msg_uuid, uuid: msg_uuid,
sender: sender.id, sender: sender.id,
type: constants.message_types.purchase, type: constants_1.default.message_types.purchase,
amount: amount || 0, amount: amount || 0,
mediaToken: mediaToken, mediaToken: mediaToken,
date: date, date: date,
@ -218,7 +218,7 @@ exports.receivePurchase = (payload) => __awaiter(void 0, void 0, void 0, functio
type: 'purchase', type: 'purchase',
response: jsonUtils.messageToJson(message, chat, sender) response: jsonUtils.messageToJson(message, chat, sender)
}); });
const isTribe = chat_type === constants.chat_types.tribe; const isTribe = chat_type === constants_1.default.chat_types.tribe;
// if sats forwarded from tribe owner, for the >1 time // if sats forwarded from tribe owner, for the >1 time
// dont need to send back token, because admin already has it // dont need to send back token, because admin already has it
if (isTribe && skip_payment_processing) { if (isTribe && skip_payment_processing) {
@ -262,14 +262,14 @@ exports.receivePurchase = (payload) => __awaiter(void 0, void 0, void 0, functio
chat: Object.assign(Object.assign({}, chat.dataValues), { contactIds: [sender.id] }), chat: Object.assign(Object.assign({}, chat.dataValues), { contactIds: [sender.id] }),
sender: owner, sender: owner,
amount: amount, amount: amount,
type: constants.message_types.purchase_deny, type: constants_1.default.message_types.purchase_deny,
message: { amount, content: 'Payment Denied', mediaToken }, message: { amount, content: 'Payment Denied', mediaToken },
success: (data) => __awaiter(void 0, void 0, void 0, function* () { success: (data) => __awaiter(void 0, void 0, void 0, function* () {
console.log('purchase_deny sent'); console.log('purchase_deny sent');
const denyMsg = yield models_1.models.Message.create({ const denyMsg = yield models_1.models.Message.create({
chatId: chat.id, chatId: chat.id,
sender: owner.id, sender: owner.id,
type: constants.message_types.purchase_deny, type: constants_1.default.message_types.purchase_deny,
mediaToken: mediaToken, mediaToken: mediaToken,
date: date, createdAt: date, updatedAt: date date: date, createdAt: date, updatedAt: date
}); });
@ -296,14 +296,14 @@ exports.receivePurchase = (payload) => __awaiter(void 0, void 0, void 0, functio
network.sendMessage({ network.sendMessage({
chat: Object.assign(Object.assign({}, chat.dataValues), { contactIds: [sender.id] }), chat: Object.assign(Object.assign({}, chat.dataValues), { contactIds: [sender.id] }),
sender: owner, sender: owner,
type: constants.message_types.purchase_accept, type: constants_1.default.message_types.purchase_accept,
message: msgToSend, message: msgToSend,
success: (data) => __awaiter(void 0, void 0, void 0, function* () { success: (data) => __awaiter(void 0, void 0, void 0, function* () {
console.log('purchase_accept sent!'); console.log('purchase_accept sent!');
const acceptMsg = yield models_1.models.Message.create({ const acceptMsg = yield models_1.models.Message.create({
chatId: chat.id, chatId: chat.id,
sender: owner.id, sender: owner.id,
type: constants.message_types.purchase_accept, type: constants_1.default.message_types.purchase_accept,
mediaToken: theMediaToken, mediaToken: theMediaToken,
date: date, createdAt: date, updatedAt: date date: date, createdAt: date, updatedAt: date
}); });
@ -341,8 +341,8 @@ exports.receivePurchaseAccept = (payload) => __awaiter(void 0, void 0, void 0, f
const msg = yield models_1.models.Message.create({ const msg = yield models_1.models.Message.create({
chatId: chat.id, chatId: chat.id,
sender: sender.id, sender: sender.id,
type: constants.message_types.purchase_accept, type: constants_1.default.message_types.purchase_accept,
status: constants.statuses.received, status: constants_1.default.statuses.received,
mediaToken, mediaToken,
mediaKey, mediaKey,
mediaType, mediaType,
@ -367,8 +367,8 @@ exports.receivePurchaseDeny = (payload) => __awaiter(void 0, void 0, void 0, fun
const msg = yield models_1.models.Message.create({ const msg = yield models_1.models.Message.create({
chatId: chat.id, chatId: chat.id,
sender: sender.id, sender: sender.id,
type: constants.message_types.purchase_deny, type: constants_1.default.message_types.purchase_deny,
status: constants.statuses.received, status: constants_1.default.statuses.received,
messageContent: 'Purchase has been denied and sats returned to you', messageContent: 'Purchase has been denied and sats returned to you',
amount: amount, amount: amount,
amountMsat: parseFloat(amount) * 1000, amountMsat: parseFloat(amount) * 1000,
@ -393,7 +393,7 @@ exports.receiveAttachment = (payload) => __awaiter(void 0, void 0, void 0, funct
const msg = { const msg = {
chatId: chat.id, chatId: chat.id,
uuid: msg_uuid, uuid: msg_uuid,
type: constants.message_types.attachment, type: constants_1.default.message_types.attachment,
sender: sender.id, sender: sender.id,
date: date, date: date,
createdAt: date, createdAt: date,
@ -409,7 +409,7 @@ exports.receiveAttachment = (payload) => __awaiter(void 0, void 0, void 0, funct
msg.mediaType = mediaType; msg.mediaType = mediaType;
if (reply_uuid) if (reply_uuid)
msg.replyUuid = reply_uuid; msg.replyUuid = reply_uuid;
const isTribe = chat_type === constants.chat_types.tribe; const isTribe = chat_type === constants_1.default.chat_types.tribe;
if (isTribe) { if (isTribe) {
msg.senderAlias = sender_alias; msg.senderAlias = sender_alias;
} }

2
dist/src/controllers/media.js.map

File diff suppressed because one or more lines are too long

33
dist/src/controllers/messages.js

@ -19,10 +19,9 @@ const helpers = require("../helpers");
const res_1 = require("../utils/res"); const res_1 = require("../utils/res");
const timers = require("../utils/timers"); const timers = require("../utils/timers");
const confirmations_1 = require("./confirmations"); const confirmations_1 = require("./confirmations");
const path = require("path");
const network = require("../network"); const network = require("../network");
const short = require("short-uuid"); const short = require("short-uuid");
const constants = require(path.join(__dirname, '../../config/constants.json')); const constants_1 = require("../constants");
exports.getMessages = (req, res) => __awaiter(void 0, void 0, void 0, function* () { exports.getMessages = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
const dateToReturn = req.query.date; const dateToReturn = req.query.date;
if (!dateToReturn) { if (!dateToReturn) {
@ -41,14 +40,14 @@ exports.getMessages = (req, res) => __awaiter(void 0, void 0, void 0, function*
let confirmedMessagesWhere = { let confirmedMessagesWhere = {
updated_at: { [sequelize_1.Op.gte]: dateToReturn }, updated_at: { [sequelize_1.Op.gte]: dateToReturn },
status: { [sequelize_1.Op.or]: [ status: { [sequelize_1.Op.or]: [
constants.statuses.received, constants_1.default.statuses.received,
] }, ] },
sender: owner.id sender: owner.id
}; };
let deletedMessagesWhere = { let deletedMessagesWhere = {
updated_at: { [sequelize_1.Op.gte]: dateToReturn }, updated_at: { [sequelize_1.Op.gte]: dateToReturn },
status: { [sequelize_1.Op.or]: [ status: { [sequelize_1.Op.or]: [
constants.statuses.deleted constants_1.default.statuses.deleted
] }, ] },
}; };
// if (chatId) { // if (chatId) {
@ -88,11 +87,11 @@ exports.getAllMessages = (req, res) => __awaiter(void 0, void 0, void 0, functio
const limit = (req.query.limit && parseInt(req.query.limit)) || 1000; const limit = (req.query.limit && parseInt(req.query.limit)) || 1000;
const offset = (req.query.offset && parseInt(req.query.offset)) || 0; const offset = (req.query.offset && parseInt(req.query.offset)) || 0;
console.log(`=> getAllMessages, limit: ${limit}, offset: ${offset}`); console.log(`=> getAllMessages, limit: ${limit}, offset: ${offset}`);
const messages = yield models_1.models.Message.findAll({ order: [['chat_id', 'asc']], limit, offset }); const messages = yield models_1.models.Message.findAll({ order: [['id', 'asc']], limit, offset });
console.log('=> got msgs', (messages && messages.length)); console.log('=> got msgs', (messages && messages.length));
const chatIds = []; const chatIds = [];
messages.forEach((m) => { messages.forEach((m) => {
if (!chatIds.includes(m.chatId)) { if (m.chatId && !chatIds.includes(m.chatId)) {
chatIds.push(m.chatId); chatIds.push(m.chatId);
} }
}); });
@ -110,7 +109,7 @@ function deleteMessage(req, res) {
const id = parseInt(req.params.id); const id = parseInt(req.params.id);
const message = yield models_1.models.Message.findOne({ where: { id } }); const message = yield models_1.models.Message.findOne({ where: { id } });
const uuid = message.uuid; const uuid = message.uuid;
yield message.update({ status: constants.statuses.deleted }); yield message.update({ status: constants_1.default.statuses.deleted });
const chat_id = message.chatId; const chat_id = message.chatId;
let chat; let chat;
if (chat_id) { if (chat_id) {
@ -119,7 +118,7 @@ function deleteMessage(req, res) {
res_1.success(res, jsonUtils.messageToJson(message, chat)); res_1.success(res, jsonUtils.messageToJson(message, chat));
if (!chat) if (!chat)
return; return;
const isTribe = chat.type === constants.chat_types.tribe; const isTribe = chat.type === constants_1.default.chat_types.tribe;
const owner = yield models_1.models.Contact.findOne({ where: { isOwner: true } }); const owner = yield models_1.models.Contact.findOne({ where: { isOwner: true } });
const isTribeOwner = isTribe && owner.publicKey === chat.ownerPubkey; const isTribeOwner = isTribe && owner.publicKey === chat.ownerPubkey;
if (isTribeOwner) { if (isTribeOwner) {
@ -128,7 +127,7 @@ function deleteMessage(req, res) {
network.sendMessage({ network.sendMessage({
chat: chat, chat: chat,
sender: owner, sender: owner,
type: constants.message_types.delete, type: constants_1.default.message_types.delete,
message: { id, uuid }, message: { id, uuid },
}); });
}); });
@ -153,13 +152,13 @@ exports.sendMessage = (req, res) => __awaiter(void 0, void 0, void 0, function*
const msg = { const msg = {
chatId: chat.id, chatId: chat.id,
uuid: short.generate(), uuid: short.generate(),
type: constants.message_types.message, type: constants_1.default.message_types.message,
sender: owner.id, sender: owner.id,
amount: amount || 0, amount: amount || 0,
date: date, date: date,
messageContent: text, messageContent: text,
remoteMessageContent, remoteMessageContent,
status: constants.statuses.pending, status: constants_1.default.statuses.pending,
createdAt: date, createdAt: date,
updatedAt: date, updatedAt: date,
}; };
@ -179,7 +178,7 @@ exports.sendMessage = (req, res) => __awaiter(void 0, void 0, void 0, function*
chat: chat, chat: chat,
sender: owner, sender: owner,
amount: amount || 0, amount: amount || 0,
type: constants.message_types.message, type: constants_1.default.message_types.message,
message: msgToSend, message: msgToSend,
}); });
}); });
@ -198,16 +197,16 @@ exports.receiveMessage = (payload) => __awaiter(void 0, void 0, void 0, function
const msg = { const msg = {
chatId: chat.id, chatId: chat.id,
uuid: msg_uuid, uuid: msg_uuid,
type: constants.message_types.message, type: constants_1.default.message_types.message,
asciiEncodedTotal: total_spent, asciiEncodedTotal: total_spent,
sender: sender.id, sender: sender.id,
date: date, date: date,
messageContent: text, messageContent: text,
createdAt: date, createdAt: date,
updatedAt: date, updatedAt: date,
status: constants.statuses.received status: constants_1.default.statuses.received
}; };
const isTribe = chat_type === constants.chat_types.tribe; const isTribe = chat_type === constants_1.default.chat_types.tribe;
if (isTribe) { if (isTribe) {
msg.senderAlias = sender_alias; msg.senderAlias = sender_alias;
if (remote_content) if (remote_content)
@ -231,7 +230,7 @@ exports.receiveDeleteMessage = (payload) => __awaiter(void 0, void 0, void 0, fu
if (!owner || !sender || !chat) { if (!owner || !sender || !chat) {
return console.log('=> no group chat!'); return console.log('=> no group chat!');
} }
const isTribe = chat_type === constants.chat_types.tribe; const isTribe = chat_type === constants_1.default.chat_types.tribe;
// in tribe this is already validated on admin's node // in tribe this is already validated on admin's node
let where = { uuid: msg_uuid }; let where = { uuid: msg_uuid };
if (!isTribe) { if (!isTribe) {
@ -240,7 +239,7 @@ exports.receiveDeleteMessage = (payload) => __awaiter(void 0, void 0, void 0, fu
const message = yield models_1.models.Message.findOne({ where }); const message = yield models_1.models.Message.findOne({ where });
if (!message) if (!message)
return; return;
yield message.update({ status: constants.statuses.deleted }); yield message.update({ status: constants_1.default.statuses.deleted });
socket.sendJson({ socket.sendJson({
type: 'delete', type: 'delete',
response: jsonUtils.messageToJson(message, chat, sender) response: jsonUtils.messageToJson(message, chat, sender)

2
dist/src/controllers/messages.js.map

File diff suppressed because one or more lines are too long

67
dist/src/controllers/payment.js

@ -15,11 +15,11 @@ const socket = require("../utils/socket");
const jsonUtils = require("../utils/json"); const jsonUtils = require("../utils/json");
const helpers = require("../helpers"); const helpers = require("../helpers");
const res_1 = require("../utils/res"); const res_1 = require("../utils/res");
const lightning = require("../utils/lightning");
const ldat_1 = require("../utils/ldat"); const ldat_1 = require("../utils/ldat");
const constants = require("../../config/constants.json");
const network = require("../network"); const network = require("../network");
const short = require("short-uuid"); const short = require("short-uuid");
const constants_1 = require("../constants");
const sequelize_1 = require("sequelize");
exports.sendPayment = (req, res) => __awaiter(void 0, void 0, void 0, function* () { exports.sendPayment = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
const { amount, chat_id, contact_id, destination_key, media_type, muid, text, remote_text, dimensions, remote_text_map, contact_ids, reply_uuid, } = req.body; const { amount, chat_id, contact_id, destination_key, media_type, muid, text, remote_text, dimensions, remote_text_map, contact_ids, reply_uuid, } = req.body;
console.log('[send payment]', req.body); console.log('[send payment]', req.body);
@ -52,7 +52,7 @@ exports.sendPayment = (req, res) => __awaiter(void 0, void 0, void 0, function*
chatId: chat.id, chatId: chat.id,
uuid: short.generate(), uuid: short.generate(),
sender: owner.id, sender: owner.id,
type: constants.message_types.direct_payment, type: constants_1.default.message_types.direct_payment,
amount: amount, amount: amount,
amountMsat: parseFloat(amount) * 1000, amountMsat: parseFloat(amount) * 1000,
date: date, date: date,
@ -99,7 +99,7 @@ exports.sendPayment = (req, res) => __awaiter(void 0, void 0, void 0, function*
network.sendMessage({ network.sendMessage({
chat: theChat, chat: theChat,
sender: owner, sender: owner,
type: constants.message_types.direct_payment, type: constants_1.default.message_types.direct_payment,
message: msgToSend, message: msgToSend,
amount: amount, amount: amount,
success: (data) => __awaiter(void 0, void 0, void 0, function* () { success: (data) => __awaiter(void 0, void 0, void 0, function* () {
@ -107,7 +107,7 @@ exports.sendPayment = (req, res) => __awaiter(void 0, void 0, void 0, function*
res_1.success(res, jsonUtils.messageToJson(message, chat)); res_1.success(res, jsonUtils.messageToJson(message, chat));
}), }),
failure: (error) => __awaiter(void 0, void 0, void 0, function* () { failure: (error) => __awaiter(void 0, void 0, void 0, function* () {
yield message.update({ status: constants.statuses.failed }); yield message.update({ status: constants_1.default.statuses.failed });
res.status(200); res.status(200);
res.json({ res.json({
success: false, success: false,
@ -128,7 +128,7 @@ exports.receivePayment = (payload) => __awaiter(void 0, void 0, void 0, function
const msg = { const msg = {
chatId: chat.id, chatId: chat.id,
uuid: msg_uuid, uuid: msg_uuid,
type: constants.message_types.direct_payment, type: constants_1.default.message_types.direct_payment,
sender: sender.id, sender: sender.id,
amount: amount, amount: amount,
amountMsat: parseFloat(amount) * 1000, amountMsat: parseFloat(amount) * 1000,
@ -142,7 +142,7 @@ exports.receivePayment = (payload) => __awaiter(void 0, void 0, void 0, function
msg.mediaType = mediaType; msg.mediaType = mediaType;
if (mediaToken) if (mediaToken)
msg.mediaToken = mediaToken; msg.mediaToken = mediaToken;
if (chat_type === constants.chat_types.tribe) { if (chat_type === constants_1.default.chat_types.tribe) {
msg.senderAlias = sender_alias; msg.senderAlias = sender_alias;
} }
if (reply_uuid) if (reply_uuid)
@ -158,44 +158,27 @@ exports.receivePayment = (payload) => __awaiter(void 0, void 0, void 0, function
exports.listPayments = (req, res) => __awaiter(void 0, void 0, void 0, function* () { exports.listPayments = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
const limit = (req.query.limit && parseInt(req.query.limit)) || 100; const limit = (req.query.limit && parseInt(req.query.limit)) || 100;
const offset = (req.query.offset && parseInt(req.query.offset)) || 0; const offset = (req.query.offset && parseInt(req.query.offset)) || 0;
const payments = []; const MIN_VAL = constants_1.default.min_sat_amount;
const MIN_VAL = 3; try {
const invs = yield lightning.listAllInvoices(); const msgs = yield models_1.models.Message.findAll({
if (invs && invs.length) { where: {
invs.forEach(inv => { type: { [sequelize_1.Op.or]: [
const val = inv.value && parseInt(inv.value); constants_1.default.message_types.payment,
if (val && val > MIN_VAL) { constants_1.default.message_types.direct_payment
let payment_hash = ''; ] },
if (inv.r_hash) { amount: {
payment_hash = Buffer.from(inv.r_hash).toString('hex'); [sequelize_1.Op.gt]: MIN_VAL // greater than
} }
payments.push({ },
type: 'invoice', order: [['createdAt', 'desc']],
amount: parseInt(inv.value), limit,
date: parseInt(inv.creation_date), offset
payment_request: inv.payment_request,
payment_hash
});
}
}); });
const ret = msgs || [];
res_1.success(res, ret.map(message => jsonUtils.messageToJson(message, null)));
} }
const pays = yield lightning.listAllPayments(); catch (e) {
if (pays && pays.length) { res_1.failure(res, 'cant find payments');
pays.forEach(pay => {
const val = pay.value && parseInt(pay.value);
if (val && val > MIN_VAL) {
payments.push({
type: 'payment',
amount: parseInt(pay.value),
date: parseInt(pay.creation_date),
// pubkey:pay.path[pay.path.length-1],
payment_hash: pay.payment_hash,
});
}
});
} }
// latest one first
payments.sort((a, b) => b.date - a.date);
res_1.success(res, payments.splice(offset, limit));
}); });
//# sourceMappingURL=payment.js.map //# sourceMappingURL=payment.js.map

2
dist/src/controllers/payment.js.map

File diff suppressed because one or more lines are too long

15
dist/src/controllers/subscriptions.js

@ -19,9 +19,8 @@ const jsonUtils = require("../utils/json");
const helpers = require("../helpers"); const helpers = require("../helpers");
const rsa = require("../crypto/rsa"); const rsa = require("../crypto/rsa");
const moment = require("moment"); const moment = require("moment");
const path = require("path");
const network = require("../network"); const network = require("../network");
const constants = require(path.join(__dirname, '../../config/constants.json')); const constants_1 = require("../constants");
// store all current running jobs in memory // store all current running jobs in memory
let jobs = {}; let jobs = {};
// init jobs from DB // init jobs from DB
@ -129,7 +128,7 @@ function sendSubscriptionPayment(sub, isFirstMessage) {
network.sendMessage({ network.sendMessage({
chat: chat, chat: chat,
sender: owner, sender: owner,
type: constants.message_types.direct_payment, type: constants_1.default.message_types.direct_payment,
message: { amount: sub.amount, content: enc }, message: { amount: sub.amount, content: enc },
amount: sub.amount, amount: sub.amount,
success: (data) => __awaiter(this, void 0, void 0, function* () { success: (data) => __awaiter(this, void 0, void 0, function* () {
@ -152,8 +151,8 @@ function sendSubscriptionPayment(sub, isFirstMessage) {
const message = yield models_1.models.Message.create({ const message = yield models_1.models.Message.create({
chatId: chat.id, chatId: chat.id,
sender: owner.id, sender: owner.id,
type: constants.message_types.direct_payment, type: constants_1.default.message_types.direct_payment,
status: constants.statuses.confirmed, status: constants_1.default.statuses.confirmed,
messageContent: encText, messageContent: encText,
amount: subscription.amount, amount: subscription.amount,
amountMsat: parseFloat(subscription.amount) * 1000, amountMsat: parseFloat(subscription.amount) * 1000,
@ -169,13 +168,13 @@ function sendSubscriptionPayment(sub, isFirstMessage) {
}), }),
failure: (err) => __awaiter(this, void 0, void 0, function* () { failure: (err) => __awaiter(this, void 0, void 0, function* () {
console.log("SEND PAY ERROR"); console.log("SEND PAY ERROR");
let errMessage = constants.payment_errors[err] || 'Unknown'; let errMessage = constants_1.default.payment_errors[err] || 'Unknown';
errMessage = 'Payment Failed: ' + errMessage; errMessage = 'Payment Failed: ' + errMessage;
const message = yield models_1.models.Message.create({ const message = yield models_1.models.Message.create({
chatId: chat.id, chatId: chat.id,
sender: owner.id, sender: owner.id,
type: constants.message_types.direct_payment, type: constants_1.default.message_types.direct_payment,
status: constants.statuses.failed, status: constants_1.default.statuses.failed,
messageContent: errMessage, messageContent: errMessage,
amount: sub.amount, amount: sub.amount,
amountMsat: parseFloat(sub.amount) * 1000, amountMsat: parseFloat(sub.amount) * 1000,

2
dist/src/controllers/subscriptions.js.map

File diff suppressed because one or more lines are too long

44
dist/src/grpc/index.js

@ -17,8 +17,7 @@ const decodeUtils = require("../utils/decode");
const lightning_1 = require("../utils/lightning"); const lightning_1 = require("../utils/lightning");
const network = require("../network"); const network = require("../network");
const moment = require("moment"); const moment = require("moment");
const path = require("path"); const constants_1 = require("../constants");
const constants = require(path.join(__dirname, '../../config/constants.json'));
const ERR_CODE_UNAVAILABLE = 14; const ERR_CODE_UNAVAILABLE = 14;
const ERR_CODE_STREAM_REMOVED = 2; const ERR_CODE_STREAM_REMOVED = 2;
function subscribeInvoices(parseKeysendInvoice) { function subscribeInvoices(parseKeysendInvoice) {
@ -35,7 +34,17 @@ function subscribeInvoices(parseKeysendInvoice) {
parseKeysendInvoice(response); parseKeysendInvoice(response);
} }
else { else {
const invoice = yield models_1.models.Message.findOne({ where: { type: constants.message_types.invoice, payment_request: response['payment_request'] } }); let decodedPaymentRequest = decodeUtils.decode(response['payment_request']);
var paymentHash = "";
for (var i = 0; i < decodedPaymentRequest["data"]["tags"].length; i++) {
let tag = decodedPaymentRequest["data"]["tags"][i];
if (tag['description'] == 'payment_hash') {
paymentHash = tag['value'];
break;
}
}
let settleDate = parseInt(response['settle_date'] + '000');
const invoice = yield models_1.models.Message.findOne({ where: { type: constants_1.default.message_types.invoice, payment_request: response['payment_request'] } });
if (invoice == null) { if (invoice == null) {
// console.log("ERROR: Invoice " + response['payment_request'] + " not found"); // console.log("ERROR: Invoice " + response['payment_request'] + " not found");
const payReq = response['payment_request']; const payReq = response['payment_request'];
@ -47,32 +56,35 @@ function subscribeInvoices(parseKeysendInvoice) {
type: 'invoice_payment', type: 'invoice_payment',
response: { invoice: payReq } response: { invoice: payReq }
}); });
yield models_1.models.Message.create({
chatId: 0,
type: constants_1.default.message_types.payment,
sender: 0,
amount: response['amt_paid_sat'],
amountMsat: response['amt_paid_msat'],
paymentHash: paymentHash,
date: new Date(settleDate),
messageContent: response['memo'],
status: constants_1.default.statuses.confirmed,
createdAt: new Date(settleDate),
updatedAt: new Date(settleDate)
});
return; return;
} }
models_1.models.Message.update({ status: constants.statuses.confirmed }, { where: { id: invoice.id } }); models_1.models.Message.update({ status: constants_1.default.statuses.confirmed }, { where: { id: invoice.id } });
let decodedPaymentRequest = decodeUtils.decode(response['payment_request']);
var paymentHash = "";
for (var i = 0; i < decodedPaymentRequest["data"]["tags"].length; i++) {
let tag = decodedPaymentRequest["data"]["tags"][i];
if (tag['description'] == 'payment_hash') {
paymentHash = tag['value'];
break;
}
}
let settleDate = parseInt(response['settle_date'] + '000');
const chat = yield models_1.models.Chat.findOne({ where: { id: invoice.chatId } }); const chat = yield models_1.models.Chat.findOne({ where: { id: invoice.chatId } });
const contactIds = JSON.parse(chat.contactIds); const contactIds = JSON.parse(chat.contactIds);
const senderId = contactIds.find(id => id != invoice.sender); const senderId = contactIds.find(id => id != invoice.sender);
const message = yield models_1.models.Message.create({ const message = yield models_1.models.Message.create({
chatId: invoice.chatId, chatId: invoice.chatId,
type: constants.message_types.payment, type: constants_1.default.message_types.payment,
sender: senderId, sender: senderId,
amount: response['amt_paid_sat'], amount: response['amt_paid_sat'],
amountMsat: response['amt_paid_msat'], amountMsat: response['amt_paid_msat'],
paymentHash: paymentHash, paymentHash: paymentHash,
date: new Date(settleDate), date: new Date(settleDate),
messageContent: response['memo'], messageContent: response['memo'],
status: constants.statuses.confirmed, status: constants_1.default.statuses.confirmed,
createdAt: new Date(settleDate), createdAt: new Date(settleDate),
updatedAt: new Date(settleDate) updatedAt: new Date(settleDate)
}); });

2
dist/src/grpc/index.js.map

File diff suppressed because one or more lines are too long

10
dist/src/helpers.js

@ -12,7 +12,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
const models_1 = require("./models"); const models_1 = require("./models");
const md5 = require("md5"); const md5 = require("md5");
const network = require("./network"); const network = require("./network");
const constants = require('../config/constants.json'); const constants_1 = require("./constants");
exports.findOrCreateChat = (params) => __awaiter(void 0, void 0, void 0, function* () { exports.findOrCreateChat = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { chat_id, owner_id, recipient_id } = params; const { chat_id, owner_id, recipient_id } = params;
let chat; let chat;
@ -35,7 +35,7 @@ exports.findOrCreateChat = (params) => __awaiter(void 0, void 0, void 0, functio
contactIds: JSON.stringify([parseInt(owner_id), parseInt(recipient_id)]), contactIds: JSON.stringify([parseInt(owner_id), parseInt(recipient_id)]),
createdAt: date, createdAt: date,
updatedAt: date, updatedAt: date,
type: constants.chat_types.conversation type: constants_1.default.chat_types.conversation
}); });
} }
} }
@ -112,7 +112,7 @@ function findOrCreateContactByPubkey(senderPubKey) {
exports.sendContactKeys({ exports.sendContactKeys({
contactIds: [sender.id], contactIds: [sender.id],
sender: owner, sender: owner,
type: constants.message_types.contact_key, type: constants_1.default.message_types.contact_key,
}); });
} }
return sender; return sender;
@ -169,7 +169,7 @@ function parseReceiveParams(payload) {
const reply_uuid = dat.message.replyUuid; const reply_uuid = dat.message.replyUuid;
const purchaser_id = dat.message.purchaser; const purchaser_id = dat.message.purchaser;
const isTribeOwner = dat.isTribeOwner ? true : false; const isTribeOwner = dat.isTribeOwner ? true : false;
const isConversation = !chat_type || (chat_type && chat_type == constants.chat_types.conversation); const isConversation = !chat_type || (chat_type && chat_type == constants_1.default.chat_types.conversation);
let sender; let sender;
let chat; let chat;
const owner = yield models_1.models.Contact.findOne({ where: { isOwner: true } }); const owner = yield models_1.models.Contact.findOne({ where: { isOwner: true } });
@ -183,7 +183,7 @@ function parseReceiveParams(payload) {
else { // group else { // group
sender = yield models_1.models.Contact.findOne({ where: { publicKey: sender_pub_key } }); sender = yield models_1.models.Contact.findOne({ where: { publicKey: sender_pub_key } });
// inject a "sender" with an alias // inject a "sender" with an alias
if (!sender && chat_type == constants.chat_types.tribe) { if (!sender && chat_type == constants_1.default.chat_types.tribe) {
sender = { id: 0, alias: sender_alias }; sender = { id: 0, alias: sender_alias };
} }
chat = yield models_1.models.Chat.findOne({ where: { uuid: chat_uuid } }); chat = yield models_1.models.Chat.findOne({ where: { uuid: chat_uuid } });

2
dist/src/helpers.js.map

File diff suppressed because one or more lines are too long

16
dist/src/hub.js

@ -18,7 +18,7 @@ const helpers = require("./helpers");
const nodeinfo_1 = require("./utils/nodeinfo"); const nodeinfo_1 = require("./utils/nodeinfo");
const lightning_1 = require("./utils/lightning"); const lightning_1 = require("./utils/lightning");
const path = require("path"); const path = require("path");
const constants = require(path.join(__dirname, '../config/constants.json')); const constants_1 = require("./constants");
const env = process.env.NODE_ENV || 'development'; const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname, '../config/app.json'))[env]; const config = require(path.join(__dirname, '../config/app.json'))[env];
const checkInviteHub = (params = {}) => __awaiter(void 0, void 0, void 0, function* () { const checkInviteHub = (params = {}) => __awaiter(void 0, void 0, void 0, function* () {
@ -27,7 +27,7 @@ const checkInviteHub = (params = {}) => __awaiter(void 0, void 0, void 0, functi
} }
const owner = yield models_1.models.Contact.findOne({ where: { isOwner: true } }); const owner = yield models_1.models.Contact.findOne({ where: { isOwner: true } });
//console.log('[hub] checking invites ping') //console.log('[hub] checking invites ping')
const inviteStrings = yield models_1.models.Invite.findAll({ where: { status: { [sequelize_1.Op.notIn]: [constants.invite_statuses.complete, constants.invite_statuses.expired] } } }).map(invite => invite.inviteString); const inviteStrings = yield models_1.models.Invite.findAll({ where: { status: { [sequelize_1.Op.notIn]: [constants_1.default.invite_statuses.complete, constants_1.default.invite_statuses.expired] } } }).map(invite => invite.inviteString);
if (inviteStrings.length === 0) { if (inviteStrings.length === 0) {
return; // skip if no invites return; // skip if no invites
} }
@ -54,12 +54,12 @@ const checkInviteHub = (params = {}) => __awaiter(void 0, void 0, void 0, functi
type: 'invite', type: 'invite',
response: jsonUtils.inviteToJson(dbInvite) response: jsonUtils.inviteToJson(dbInvite)
}); });
if (dbInvite.status == constants.invite_statuses.ready && contact) { if (dbInvite.status == constants_1.default.invite_statuses.ready && contact) {
sendNotification(-1, contact.alias, 'invite'); sendNotification(-1, contact.alias, 'invite');
} }
} }
if (pubkey && dbInvite.status == constants.invite_statuses.complete && contact) { if (pubkey && dbInvite.status == constants_1.default.invite_statuses.complete && contact) {
contact.update({ publicKey: pubkey, status: constants.contact_statuses.confirmed }); contact.update({ publicKey: pubkey, status: constants_1.default.contact_statuses.confirmed });
var contactJson = jsonUtils.contactToJson(contact); var contactJson = jsonUtils.contactToJson(contact);
contactJson.invite = jsonUtils.inviteToJson(dbInvite); contactJson.invite = jsonUtils.inviteToJson(dbInvite);
socket.sendJson({ socket.sendJson({
@ -69,7 +69,7 @@ const checkInviteHub = (params = {}) => __awaiter(void 0, void 0, void 0, functi
helpers.sendContactKeys({ helpers.sendContactKeys({
contactIds: [contact.id], contactIds: [contact.id],
sender: owner, sender: owner,
type: constants.message_types.contact_key, type: constants_1.default.message_types.contact_key,
}); });
} }
})); }));
@ -201,7 +201,7 @@ const sendNotification = (chat, name, type) => __awaiter(void 0, void 0, void 0,
if (type === 'keysend') { if (type === 'keysend') {
message = `You have received a keysend payment`; message = `You have received a keysend payment`;
} }
if (type === 'message' && chat.type == constants.chat_types.group && chat.name && chat.name.length) { if (type === 'message' && chat.type == constants_1.default.chat_types.group && chat.name && chat.name.length) {
message += ` on ${chat.name}`; message += ` on ${chat.name}`;
} }
const owner = yield models_1.models.Contact.findOne({ where: { isOwner: true } }); const owner = yield models_1.models.Contact.findOne({ where: { isOwner: true } });
@ -226,7 +226,7 @@ const sendNotification = (chat, name, type) => __awaiter(void 0, void 0, void 0,
return; // skip on Android if no actual message return; // skip on Android if no actual message
} }
params.notification = notification; params.notification = notification;
if (type === 'message' && chat.type == constants.chat_types.tribe) { if (type === 'message' && chat.type == constants_1.default.chat_types.tribe) {
debounce(() => { debounce(() => {
const count = tribeCounts[chat.id] ? tribeCounts[chat.id] + ' ' : ''; const count = tribeCounts[chat.id] ? tribeCounts[chat.id] + ' ' : '';
params.notification.message = chat.isMuted ? '' : `You have ${count}new messages in ${chat.name}`; params.notification.message = chat.isMuted ? '' : `You have ${count}new messages in ${chat.name}`;

2
dist/src/hub.js.map

File diff suppressed because one or more lines are too long

15
dist/src/network/intercept.js

@ -12,9 +12,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
const models_1 = require("../models"); const models_1 = require("../models");
const builtin_1 = require("../builtin"); const builtin_1 = require("../builtin");
const bots_1 = require("../controllers/bots"); const bots_1 = require("../controllers/bots");
const path = require("path");
const SphinxBot = require("sphinx-bot"); const SphinxBot = require("sphinx-bot");
const constants = require(path.join(__dirname, '../../config/constants.json')); const constants_1 = require("../constants");
/* /*
default show or not default show or not
restrictions (be able to toggle, or dont show chat) restrictions (be able to toggle, or dont show chat)
@ -24,7 +23,7 @@ function isBotMsg(msg, sentByMe) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const txt = msg.message && msg.message.content; const txt = msg.message && msg.message.content;
const msgType = msg.type; const msgType = msg.type;
if (msgType === constants.message_types.bot_res) { if (msgType === constants_1.default.message_types.bot_res) {
return false; // bot res msg type not for processing return false; // bot res msg type not for processing
} }
const chat = yield models_1.models.Chat.findOne({ const chat = yield models_1.models.Chat.findOne({
@ -55,8 +54,8 @@ function isBotMsg(msg, sentByMe) {
try { try {
const msgTypes = JSON.parse(botInTribe.msgTypes); const msgTypes = JSON.parse(botInTribe.msgTypes);
if (msgTypes.includes(msgType)) { if (msgTypes.includes(msgType)) {
const isMsgAndHasText = msgType === constants.message_types.message && txt && txt.startsWith(`${botInTribe.botPrefix} `); const isMsgAndHasText = msgType === constants_1.default.message_types.message && txt && txt.startsWith(`${botInTribe.botPrefix} `);
const isNotMsg = msgType !== constants.message_types.message; const isNotMsg = msgType !== constants_1.default.message_types.message;
if (isMsgAndHasText || isNotMsg) { if (isMsgAndHasText || isNotMsg) {
didEmit = yield emitMessageToBot(msg, botInTribe.dataValues); didEmit = yield emitMessageToBot(msg, botInTribe.dataValues);
} }
@ -79,17 +78,17 @@ function emitMessageToBot(msg, botInTribe) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
// console.log('=> emitMessageToBot',JSON.stringify(msg,null,2)) // console.log('=> emitMessageToBot',JSON.stringify(msg,null,2))
switch (botInTribe.botType) { switch (botInTribe.botType) {
case constants.bot_types.builtin: case constants_1.default.bot_types.builtin:
builtin_1.builtinBotEmit(msg); builtin_1.builtinBotEmit(msg);
return true; return true;
case constants.bot_types.local: case constants_1.default.bot_types.local:
const bot = yield models_1.models.Bot.findOne({ const bot = yield models_1.models.Bot.findOne({
where: { where: {
uuid: botInTribe.botUuid uuid: botInTribe.botUuid
} }
}); });
return bots_1.postToBotServer(msg, bot, SphinxBot.MSG_TYPE.MESSAGE); return bots_1.postToBotServer(msg, bot, SphinxBot.MSG_TYPE.MESSAGE);
case constants.bot_types.remote: case constants_1.default.bot_types.remote:
return bots_1.keysendBotCmd(msg, botInTribe); return bots_1.keysendBotCmd(msg, botInTribe);
default: default:
return false; return false;

2
dist/src/network/intercept.js.map

@ -1 +1 @@
{"version":3,"file":"intercept.js","sourceRoot":"","sources":["../../../src/network/intercept.ts"],"names":[],"mappings":";;;;;;;;;;;AACA,sCAAkC;AAClC,wCAA2C;AAC3C,8CAAoE;AACpE,6BAA4B;AAC5B,wCAAuC;AAEvC,MAAM,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,6BAA6B,CAAC,CAAC,CAAA;AAE9E;;;EAGE;AAEF,kDAAkD;AAClD,SAAsB,QAAQ,CAAC,GAAQ,EAAE,QAAiB;;QACxD,MAAM,GAAG,GAAG,GAAG,CAAC,OAAO,IAAI,GAAG,CAAC,OAAO,CAAC,OAAO,CAAA;QAE9C,MAAM,OAAO,GAAG,GAAG,CAAC,IAAI,CAAA;QACxB,IAAI,OAAO,KAAK,SAAS,CAAC,aAAa,CAAC,OAAO,EAAE;YAC/C,OAAO,KAAK,CAAA,CAAC,sCAAsC;SACpD;QACD,MAAM,IAAI,GAAG,MAAM,eAAM,CAAC,IAAI,CAAC,OAAO,CAAC;YACrC,KAAK,EAAE;gBACL,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,IAAI;aACpB;SACF,CAAC,CAAA;QACF,IAAI,CAAC,IAAI;YAAE,OAAO,KAAK,CAAA;QAEvB,IAAI,OAAO,GAAG,KAAK,CAAA;QAEnB,IAAI,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE;YAClC,wBAAc,CAAC,GAAG,CAAC,CAAA;YACnB,OAAO,GAAG,IAAI,CAAA;SACf;QACD,IAAI,OAAO;YAAE,OAAO,OAAO,CAAA;QAE3B,MAAM,WAAW,GAAG,MAAM,eAAM,C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E,KAAK,GAAG,KAAK,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE;YACjD,MAAM,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;SAC5C;IACH,CAAC;CAAA"}

15
dist/src/network/modify.js

@ -9,7 +9,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}); });
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const path = require("path");
const node_fetch_1 = require("node-fetch"); const node_fetch_1 = require("node-fetch");
const ldat_1 = require("../utils/ldat"); const ldat_1 = require("../utils/ldat");
const rsa = require("../crypto/rsa"); const rsa = require("../crypto/rsa");
@ -20,8 +19,8 @@ const models_1 = require("../models");
const RNCryptor = require("jscryptor"); const RNCryptor = require("jscryptor");
const send_1 = require("./send"); const send_1 = require("./send");
// import { Op } from 'sequelize' // import { Op } from 'sequelize'
const constants = require(path.join(__dirname, '../../config/constants.json')); const constants_1 = require("../constants");
const msgtypes = constants.message_types; const msgtypes = constants_1.default.message_types;
function modifyPayloadAndSaveMediaKey(payload, chat, sender) { function modifyPayloadAndSaveMediaKey(payload, chat, sender) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
if (payload.type !== msgtypes.attachment) if (payload.type !== msgtypes.attachment)
@ -69,7 +68,7 @@ function purchaseFromOriginalSender(payload, chat, purchaser) {
send_1.sendMessage({ send_1.sendMessage({
chat: Object.assign(Object.assign({}, chat.dataValues), { contactIds: [purchaser.id] }), chat: Object.assign(Object.assign({}, chat.dataValues), { contactIds: [purchaser.id] }),
sender: owner, sender: owner,
type: constants.message_types.purchase_accept, type: constants_1.default.message_types.purchase_accept,
message: msg, message: msg,
success: () => { }, success: () => { },
failure: () => { } failure: () => { }
@ -78,7 +77,7 @@ function purchaseFromOriginalSender(payload, chat, purchaser) {
send_1.sendMessage({ send_1.sendMessage({
chat: Object.assign(Object.assign({}, chat.dataValues), { contactIds: [mediaKey.sender] }), chat: Object.assign(Object.assign({}, chat.dataValues), { contactIds: [mediaKey.sender] }),
sender: owner, sender: owner,
type: constants.message_types.purchase, type: constants_1.default.message_types.purchase,
amount: amount, amount: amount,
message: { message: {
mediaToken: mt, mediaToken: mt,
@ -96,8 +95,8 @@ function purchaseFromOriginalSender(payload, chat, purchaser) {
const msg = { mediaToken: mt, purchaser: purchaser.id }; const msg = { mediaToken: mt, purchaser: purchaser.id };
send_1.sendMessage({ send_1.sendMessage({
chat: Object.assign(Object.assign({}, chat.dataValues), { contactIds: [ogmsg.sender] }), chat: Object.assign(Object.assign({}, chat.dataValues), { contactIds: [ogmsg.sender] }),
sender: Object.assign(Object.assign(Object.assign({}, owner.dataValues), purchaser && purchaser.alias && { alias: purchaser.alias }), { role: constants.chat_roles.reader }), sender: Object.assign(Object.assign(Object.assign({}, owner.dataValues), purchaser && purchaser.alias && { alias: purchaser.alias }), { role: constants_1.default.chat_roles.reader }),
type: constants.message_types.purchase, type: constants_1.default.message_types.purchase,
message: msg, message: msg,
amount: amount, amount: amount,
success: () => { }, success: () => { },
@ -139,7 +138,7 @@ function sendFinalMemeIfFirstPurchaser(payload, chat, sender) {
// send it to the purchaser // send it to the purchaser
const owner = yield models_1.models.Contact.findOne({ where: { isOwner: true } }); const owner = yield models_1.models.Contact.findOne({ where: { isOwner: true } });
send_1.sendMessage({ send_1.sendMessage({
sender: Object.assign(Object.assign(Object.assign({}, owner.dataValues), sender && sender.alias && { alias: sender.alias }), { role: constants.chat_roles.reader }), sender: Object.assign(Object.assign(Object.assign({}, owner.dataValues), sender && sender.alias && { alias: sender.alias }), { role: constants_1.default.chat_roles.reader }),
chat: Object.assign(Object.assign({}, chat.dataValues), { contactIds: [ogPurchaser.id] }), chat: Object.assign(Object.assign({}, chat.dataValues), { contactIds: [ogPurchaser.id] }),
type: msgtypes.purchase_accept, type: msgtypes.purchase_accept,
message: Object.assign(Object.assign({}, termsAndKey), { mediaType: typ, originalMuid: muid }), message: Object.assign(Object.assign({}, termsAndKey), { mediaType: typ, originalMuid: muid }),

2
dist/src/network/modify.js.map

File diff suppressed because one or more lines are too long

50
dist/src/network/receive.js

@ -9,7 +9,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}); });
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const path = require("path");
const lndService = require("../grpc"); const lndService = require("../grpc");
const lightning_1 = require("../utils/lightning"); const lightning_1 = require("../utils/lightning");
const controllers_1 = require("../controllers"); const controllers_1 = require("../controllers");
@ -24,13 +23,14 @@ const sequelize_1 = require("sequelize");
const timers = require("../utils/timers"); const timers = require("../utils/timers");
const socket = require("../utils/socket"); const socket = require("../utils/socket");
const hub_1 = require("../hub"); const hub_1 = require("../hub");
const decodeUtils = require("../utils/decode");
const constants_1 = require("../constants");
/* /*
delete type: delete type:
owner needs to check that the delete is the one who made the msg owner needs to check that the delete is the one who made the msg
in receiveDeleteMessage check the deleter is og sender? in receiveDeleteMessage check the deleter is og sender?
*/ */
const constants = require(path.join(__dirname, '../../config/constants.json')); const msgtypes = constants_1.default.message_types;
const msgtypes = constants.message_types;
exports.typesToForward = [ exports.typesToForward = [
msgtypes.message, msgtypes.group_join, msgtypes.group_leave, msgtypes.message, msgtypes.group_join, msgtypes.group_leave,
msgtypes.attachment, msgtypes.delete, msgtypes.attachment, msgtypes.delete,
@ -48,13 +48,13 @@ exports.typesToReplay = [
msgtypes.bot_res, msgtypes.bot_res,
]; ];
const botTypes = [ const botTypes = [
constants.message_types.bot_install, constants_1.default.message_types.bot_install,
constants.message_types.bot_cmd, constants_1.default.message_types.bot_cmd,
constants.message_types.bot_res, constants_1.default.message_types.bot_res,
]; ];
const botMakerTypes = [ const botMakerTypes = [
constants.message_types.bot_install, constants_1.default.message_types.bot_install,
constants.message_types.bot_cmd, constants_1.default.message_types.bot_cmd,
]; ];
function onReceive(payload) { function onReceive(payload) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
@ -77,7 +77,7 @@ function onReceive(payload) {
let isTribeOwner = false; let isTribeOwner = false;
let chat; let chat;
if (payload.chat && payload.chat.uuid) { if (payload.chat && payload.chat.uuid) {
isTribe = payload.chat.type === constants.chat_types.tribe; isTribe = payload.chat.type === constants_1.default.chat_types.tribe;
chat = yield models_1.models.Chat.findOne({ where: { uuid: payload.chat.uuid } }); chat = yield models_1.models.Chat.findOne({ where: { uuid: payload.chat.uuid } });
if (chat) if (chat)
chat.update({ seen: false }); chat.update({ seen: false });
@ -118,7 +118,7 @@ function onReceive(payload) {
doAction = false; doAction = false;
if (chat.private) { // check if has been approved if (chat.private) { // check if has been approved
const senderMember = senderContact && (yield models_1.models.ChatMember.findOne({ where: { contactId: senderContact.id, chatId: chat.id } })); const senderMember = senderContact && (yield models_1.models.ChatMember.findOne({ where: { contactId: senderContact.id, chatId: chat.id } }));
if (!(senderMember && senderMember.status === constants.chat_statuses.approved)) { if (!(senderMember && senderMember.status === constants_1.default.chat_statuses.approved)) {
doAction = false; // dont let if private and not approved doAction = false; // dont let if private and not approved
} }
} }
@ -210,7 +210,7 @@ function forwardMessageToTribe(ogpayload, sender) {
// ASK xref TABLE and put alias there too? // ASK xref TABLE and put alias there too?
send_1.sendMessage({ send_1.sendMessage({
type, message, type, message,
sender: Object.assign(Object.assign(Object.assign({}, owner.dataValues), payload.sender && payload.sender.alias && { alias: payload.sender.alias }), { role: constants.chat_roles.reader }), sender: Object.assign(Object.assign(Object.assign({}, owner.dataValues), payload.sender && payload.sender.alias && { alias: payload.sender.alias }), { role: constants_1.default.chat_roles.reader }),
chat: chat, chat: chat,
skipPubKey: payload.sender.pub_key, skipPubKey: payload.sender.pub_key,
success: () => { }, success: () => { },
@ -277,6 +277,33 @@ function parseAndVerifyPayload(data) {
} }
}); });
} }
function saveAnonymousKeysend(response) {
return __awaiter(this, void 0, void 0, function* () {
let decodedPaymentRequest = decodeUtils.decode(response['payment_request']);
var paymentHash = "";
for (var i = 0; i < decodedPaymentRequest["data"]["tags"].length; i++) {
let tag = decodedPaymentRequest["data"]["tags"][i];
if (tag['description'] == 'payment_hash') {
paymentHash = tag['value'];
break;
}
}
let settleDate = parseInt(response['settle_date'] + '000');
yield models_1.models.Message.create({
chatId: 0,
type: constants_1.default.message_types.direct_payment,
sender: 0,
amount: response['amt_paid_sat'],
amountMsat: response['amt_paid_msat'],
paymentHash: paymentHash,
date: new Date(settleDate),
messageContent: response['memo'],
status: constants_1.default.statuses.confirmed,
createdAt: new Date(settleDate),
updatedAt: new Date(settleDate)
});
});
}
function parseKeysendInvoice(i) { function parseKeysendInvoice(i) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const recs = i.htlcs && i.htlcs[0] && i.htlcs[0].custom_records; const recs = i.htlcs && i.htlcs[0] && i.htlcs[0].custom_records;
@ -289,6 +316,7 @@ function parseKeysendInvoice(i) {
response: { amount: value || 0 } response: { amount: value || 0 }
}); });
hub_1.sendNotification(-1, '', 'keysend'); hub_1.sendNotification(-1, '', 'keysend');
saveAnonymousKeysend(i);
return; return;
} }
let payload; let payload;

2
dist/src/network/receive.js.map

File diff suppressed because one or more lines are too long

22
dist/src/network/send.js

@ -13,23 +13,21 @@ const models_1 = require("../models");
const LND = require("../utils/lightning"); const LND = require("../utils/lightning");
const signer = require("../utils/signer"); const signer = require("../utils/signer");
const msg_1 = require("../utils/msg"); const msg_1 = require("../utils/msg");
const path = require("path");
const tribes = require("../utils/tribes"); const tribes = require("../utils/tribes");
const confirmations_1 = require("../controllers/confirmations"); const confirmations_1 = require("../controllers/confirmations");
const receive_1 = require("./receive"); const receive_1 = require("./receive");
const intercept = require("./intercept"); const intercept = require("./intercept");
const constants = require(path.join(__dirname, '../../config/constants.json')); const constants_1 = require("../constants");
const MIN_SATS = 3;
function sendMessage(params) { function sendMessage(params) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const { type, chat, message, sender, amount, success, failure, skipPubKey, isForwarded } = params; const { type, chat, message, sender, amount, success, failure, skipPubKey, isForwarded } = params;
if (!chat || !sender) if (!chat || !sender)
return; return;
const isTribe = chat.type === constants.chat_types.tribe; const isTribe = chat.type === constants_1.default.chat_types.tribe;
let isTribeOwner = isTribe && sender.publicKey === chat.ownerPubkey; let isTribeOwner = isTribe && sender.publicKey === chat.ownerPubkey;
let theSender = (sender.dataValues || sender); let theSender = (sender.dataValues || sender);
if (isTribeOwner && !isForwarded) { if (isTribeOwner && !isForwarded) {
theSender = Object.assign(Object.assign({}, (sender.dataValues || sender)), { role: constants.chat_roles.owner }); theSender = Object.assign(Object.assign({}, (sender.dataValues || sender)), { role: constants_1.default.chat_roles.owner });
} }
let msg = newmsg(type, chat, theSender, message); let msg = newmsg(type, chat, theSender, message);
// console.log("=> MSG TO SEND",msg) // console.log("=> MSG TO SEND",msg)
@ -49,7 +47,7 @@ function sendMessage(params) {
let networkType = undefined; let networkType = undefined;
const chatUUID = chat.uuid; const chatUUID = chat.uuid;
if (isTribe) { if (isTribe) {
if (type === constants.message_types.confirmation) { if (type === constants_1.default.message_types.confirmation) {
// if u are owner, go ahead! // if u are owner, go ahead!
if (!isTribeOwner) if (!isTribeOwner)
return; // dont send confs for tribe if not owner return; // dont send confs for tribe if not owner
@ -90,7 +88,7 @@ function sendMessage(params) {
console.log('-> sending to ', contact.id, destkey); console.log('-> sending to ', contact.id, destkey);
let mqttTopic = networkType === 'mqtt' ? `${destkey}/${chatUUID}` : ''; let mqttTopic = networkType === 'mqtt' ? `${destkey}/${chatUUID}` : '';
// sending a payment to one subscriber (like buying a pic) // sending a payment to one subscriber (like buying a pic)
if (isTribeOwner && contactIds.length === 1 && amount && amount > MIN_SATS) { if (isTribeOwner && contactIds.length === 1 && amount && amount > constants_1.default.min_sat_amount) {
mqttTopic = ''; // FORCE KEYSEND!!! mqttTopic = ''; // FORCE KEYSEND!!!
} }
const m = yield msg_1.personalizeMessage(msg, contact, isTribeOwner); const m = yield msg_1.personalizeMessage(msg, contact, isTribeOwner);
@ -98,7 +96,7 @@ function sendMessage(params) {
const opts = { const opts = {
dest: destkey, dest: destkey,
data: m, data: m,
amt: Math.max((amount || 0), MIN_SATS) amt: Math.max((amount || 0), constants_1.default.min_sat_amount)
}; };
try { try {
const r = yield signAndSend(opts, mqttTopic); const r = yield signAndSend(opts, mqttTopic);
@ -159,15 +157,15 @@ function signAndSend(opts, mqttTopic, replayingHistory) {
exports.signAndSend = signAndSend; exports.signAndSend = signAndSend;
function checkIfAutoConfirm(data) { function checkIfAutoConfirm(data) {
if (receive_1.typesToForward.includes(data.type)) { if (receive_1.typesToForward.includes(data.type)) {
if (data.type === constants.message_types.delete) { if (data.type === constants_1.default.message_types.delete) {
return; // dont auto confirm delete msg return; // dont auto confirm delete msg
} }
confirmations_1.tribeOwnerAutoConfirmation(data.message.id, data.chat.uuid); confirmations_1.tribeOwnerAutoConfirmation(data.message.id, data.chat.uuid);
} }
} }
function newmsg(type, chat, sender, message) { function newmsg(type, chat, sender, message) {
const includeGroupKey = type === constants.message_types.group_create || type === constants.message_types.group_invite; const includeGroupKey = type === constants_1.default.message_types.group_create || type === constants_1.default.message_types.group_invite;
const includeAlias = sender && sender.alias && chat.type === constants.chat_types.tribe; const includeAlias = sender && sender.alias && chat.type === constants_1.default.chat_types.tribe;
// const includePhotoUrl = sender && sender.photoUrl && !sender.privatePhoto // const includePhotoUrl = sender && sender.photoUrl && !sender.privatePhoto
return { return {
type: type, type: type,
@ -176,7 +174,7 @@ function newmsg(type, chat, sender, message) {
sender: { sender: {
pub_key: sender.publicKey, pub_key: sender.publicKey,
alias: includeAlias ? sender.alias : '', alias: includeAlias ? sender.alias : '',
role: sender.role || constants.chat_roles.reader, role: sender.role || constants_1.default.chat_roles.reader,
} }
}; };
} }

2
dist/src/network/send.js.map

File diff suppressed because one or more lines are too long

5
dist/src/utils/msg.js

@ -10,9 +10,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const ldat_1 = require("./ldat"); const ldat_1 = require("./ldat");
const path = require("path");
const rsa = require("../crypto/rsa"); const rsa = require("../crypto/rsa");
const constants = require(path.join(__dirname, '../../config/constants.json')); const constants_1 = require("../constants");
function addInRemoteText(full, contactId, isTribe) { function addInRemoteText(full, contactId, isTribe) {
const m = full && full.message; const m = full && full.message;
if (!(m && m.content)) if (!(m && m.content))
@ -152,7 +151,7 @@ function personalizeMessage(m, contact, isTribeOwner) {
const destkey = contact.publicKey; const destkey = contact.publicKey;
const cloned = JSON.parse(JSON.stringify(m)); const cloned = JSON.parse(JSON.stringify(m));
const chat = cloned && cloned.chat; const chat = cloned && cloned.chat;
const isTribe = chat.type && chat.type === constants.chat_types.tribe; const isTribe = chat.type && chat.type === constants_1.default.chat_types.tribe;
const msgWithRemoteTxt = addInRemoteText(cloned, contactId, isTribe); const msgWithRemoteTxt = addInRemoteText(cloned, contactId, isTribe);
const cleanMsg = removeRecipientFromChatMembers(msgWithRemoteTxt, destkey); const cleanMsg = removeRecipientFromChatMembers(msgWithRemoteTxt, destkey);
const cleanerMsg = removeAllNonAdminMembersIfTribe(cleanMsg, destkey); const cleanerMsg = removeAllNonAdminMembersIfTribe(cleanMsg, destkey);

2
dist/src/utils/msg.js.map

File diff suppressed because one or more lines are too long

5
dist/src/utils/timers.js

@ -11,8 +11,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const models_1 = require("../models"); const models_1 = require("../models");
const network = require("../network"); const network = require("../network");
const path = require("path"); const constants_1 = require("../constants");
const constants = require(path.join(__dirname, '../../config/constants.json'));
const timerz = {}; const timerz = {};
function clearTimer(t) { function clearTimer(t) {
const name = makeName(t); const name = makeName(t);
@ -100,7 +99,7 @@ function payBack(t) {
sender: owner, sender: owner,
message: { id: t.msgId, amount: t.amount }, message: { id: t.msgId, amount: t.amount },
amount: t.amount, amount: t.amount,
type: constants.message_types.repayment, type: constants_1.default.message_types.repayment,
}); });
models_1.models.Timer.destroy({ where: { id: t.id } }); models_1.models.Timer.destroy({ where: { id: t.id } });
}); });

2
dist/src/utils/timers.js.map

@ -1 +1 @@
{"version":3,"file":"timers.js","sourceRoot":"","sources":["../../../src/utils/timers.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,sCAAkC;AAClC,sCAAqC;AACrC,6BAA4B;AAE5B,MAAM,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAC,6BAA6B,CAAC,CAAC,CAAA;AAE7E,MAAM,MAAM,GAAC,EAAE,CAAA;AACf,SAAS,UAAU,CAAC,CAAC;IACjB,MAAM,IAAI,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAA;IACxB,IAAG,IAAI;QAAE,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAA;AACvC,CAAC;AACD,SAAsB,kBAAkB,CAAC,KAAK;;QAC1C,MAAM,CAAC,GAAG,MAAM,eAAM,CAAC,KAAK,CAAC,OAAO,CAAC,EAAC,KAAK,EAAC,EAAC,KAAK,EAAC,EAAC,CAAC,CAAA;QACrD,UAAU,CAAC,CAAC,CAAC,CAAA;QACb,eAAM,CAAC,KAAK,CAAC,OAAO,CAAC,EAAC,KAAK,EAAC,EAAC,KAAK,EAAC,EAAC,CAAC,CAAA;IACzC,CAAC;CAAA;AAJD,gDAIC;AACD,SAAsB,uBAAuB,CAAC,SAAS;;QACnD,MAAM,EAAE,GAAG,MAAM,eAAM,CAAC,KAAK,CAAC,OAAO,CAAC,EAAC,KAAK,EAAC,EAAC,QAAQ,EAAC,SAAS,EAAC,EAAC,CAAC,CAAA;QACnE,EAAE,CAAC,OAAO,CAAC,CAAC,CAAA,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAA;QAC7B,eAAM,CAAC,KAAK,CAAC,OAAO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CAAA;QACH,CAAC,CAAC,CAAA;IACH,CAAC;CAAA;AAVD,oCAUC;AACD,SAAsB,OAAO,CAAC,CAAC;;QAC3B,MAAM,IAAI,GAAG,MAAM,eAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,EAAC,EAAE,EAAC,CAAC,CAAC,MAAM,EAAC,EAAE,CAAC,CAAA;QAChE,MAAM,KAAK,GAAG,MAAM,eAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,EAAC,OAAO,EAAC,IAAI,EAAC,EAAE,CAAC,CAAA;QACrE,IAAG,CAAC,IAAI,EAAE;YACN,eAAM,CAAC,KAAK,CAAC,OAAO,CAAC,EAAC,KAAK,EAAC,EAAC,EAAE,EAAC,CAAC,CAAC,EAAE,EAAC,EAAC,CAAC,CAAA;YACvC,OAAM;SACT;QACD,MAAM,OAAO,mCAAO,IAAI,CAAC,UAAU,KAAE,UAAU,EAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAC,CAAA;QAC7D,OAAO,CAAC,WAAW,CAAC;YAChB,IAAI,EAAE,OAAO;YACb,MAAM,EAAE,KAAK;YACb,OAAO,EAAE,EAAC,EAAE,EAAC,CAAC,CAAC,KAAK,EAAC,MAAM,EAAC,CAAC,CAAC,MAAM,EAAC;YACrC,MAAM,EAAE,CAAC,CAAC,MAAM;YAChB,IAAI,EAAE,mBAAS,CAAC,aAAa,CAAC,SAAS;SAC1C,CAAC,CAAA;QACF,eAAM,CAAC,KAAK,CAAC,OAAO,CAAC,EAAC,KAAK,EAAC,EAAC,EAAE,EAAC,CAAC,CAAC,EAAE,EAAC,EAAC,CAAC,CAAA;IAC3C,CAAC;CAAA;AAhBD,0BAgBC"}

4
src/builtin/index.ts

@ -4,11 +4,9 @@ import * as MotherBot from './mother'
import * as WelcomeBot from './welcome' import * as WelcomeBot from './welcome'
import * as LoopBot from './loop' import * as LoopBot from './loop'
import {Msg} from '../network/interfaces' import {Msg} from '../network/interfaces'
import * as path from 'path'
import { models } from '../models' import { models } from '../models'
import {buildBotPayload} from '../controllers/bots' import {buildBotPayload} from '../controllers/bots'
import constants from '../constants'
const constants = require(path.join(__dirname, '../../config/constants.json'))
async function init(){ async function init(){
MotherBot.init() MotherBot.init()

3
src/builtin/mother.ts

@ -7,10 +7,11 @@ import * as WelcomeBot from './welcome'
import * as LoopBot from './loop' import * as LoopBot from './loop'
import { models } from '../models' import { models } from '../models'
import fetch from 'node-fetch' import fetch from 'node-fetch'
import constants from '../constants'
const msg_types = Sphinx.MSG_TYPE const msg_types = Sphinx.MSG_TYPE
const env = process.env.NODE_ENV || 'development' const env = process.env.NODE_ENV || 'development'
const constants = require(path.join(__dirname, '../../config/constants.json'))
const config = require(path.join(__dirname, '../../config/app.json'))[env] const config = require(path.join(__dirname, '../../config/app.json'))[env]
const builtinBots = [ const builtinBots = [

5
src/builtin/welcome.ts

@ -1,10 +1,9 @@
import * as Sphinx from 'sphinx-bot' import * as Sphinx from 'sphinx-bot'
import { finalAction } from '../controllers/api' import { finalAction } from '../controllers/api'
import { models } from '../models' import { models } from '../models'
import * as path from 'path' import constants from '../constants'
const msg_types = Sphinx.MSG_TYPE
const constants = require(path.join(__dirname, '../../config/constants.json')) const msg_types = Sphinx.MSG_TYPE
let initted = false let initted = false

86
src/constants.ts

@ -0,0 +1,86 @@
const constants = {
min_sat_amount: 3,
invite_statuses: {
"pending": 0,
"ready": 1,
"delivered": 2,
"in_progress": 3,
"complete": 4,
"expired": 5,
"payment_pending": 6
},
contact_statuses: {
"pending": 0,
"confirmed": 1
},
statuses: {
"pending": 0,
"confirmed": 1,
"cancelled": 2,
"received": 3,
"failed": 4,
"deleted": 5
},
chat_statuses: {
"approved": 0,
"pending": 1,
"rejected": 2
},
message_types: {
"message": 0,
"confirmation": 1,
"invoice": 2,
"payment": 3,
"cancellation": 4,
"direct_payment": 5,
"attachment": 6,
"purchase": 7,
"purchase_accept": 8,
"purchase_deny": 9,
"contact_key": 10,
"contact_key_confirmation": 11,
"group_create": 12,
"group_invite": 13,
"group_join": 14,
"group_leave": 15,
"group_kick": 16,
"delete": 17,
"repayment": 18,
"member_request": 19,
"member_approve": 20,
"member_reject": 21,
"tribe_delete": 22,
"bot_install": 23,
"bot_cmd": 24,
"bot_res": 25,
"heartbeat": 26,
"heartbeat_confirmation": 27
},
payment_errors: {
"timeout": "Timed Out",
"no_route": "No Route To Receiver",
"error": "Error",
"incorrect_payment_details": "Incorrect Payment Details",
"unknown": "Unknown"
},
chat_types: {
"conversation": 0,
"group": 1,
"tribe": 2
},
bot_types: {
"builtin": 0,
"local": 1,
"remote": 2
},
chat_roles: {
"-": 0,
"owner": 1,
"admin": 2,
"mod": 3,
"writer": 4,
"reader": 5
}
}
export default constants

9
src/controllers/api.ts

@ -1,4 +1,3 @@
import * as path from 'path'
import * as network from '../network' import * as network from '../network'
import { models } from '../models' import { models } from '../models'
import * as short from 'short-uuid' import * as short from 'short-uuid'
@ -6,14 +5,13 @@ import * as rsa from '../crypto/rsa'
import * as jsonUtils from '../utils/json' import * as jsonUtils from '../utils/json'
import * as socket from '../utils/socket' import * as socket from '../utils/socket'
import { success, failure } from '../utils/res' import { success, failure } from '../utils/res'
import constants from '../constants'
/* /*
hexdump -n 8 -e '4/4 "%08X" 1 "\n"' /dev/random hexdump -n 8 -e '4/4 "%08X" 1 "\n"' /dev/random
hexdump -n 16 -e '4/4 "%08X" 1 "\n"' /dev/random hexdump -n 16 -e '4/4 "%08X" 1 "\n"' /dev/random
*/ */
const constants = require(path.join(__dirname, '../../config/constants.json'))
export interface Action { export interface Action {
action: string action: string
chat_uuid: string chat_uuid: string
@ -114,12 +112,11 @@ export async function finalAction(a:Action, bot_id:string){
if (!(pubkey && pubkey.length === 66 && amount)) { if (!(pubkey && pubkey.length === 66 && amount)) {
throw 'wrong params' throw 'wrong params'
} }
const MIN_SATS = 3
const destkey = pubkey const destkey = pubkey
const opts = { const opts = {
dest: destkey, dest: destkey,
data: {}, data: {},
amt: Math.max((amount || 0), MIN_SATS) amt: Math.max((amount || 0), constants.min_sat_amount)
} }
try { try {
await network.signAndSend(opts) await network.signAndSend(opts)
@ -132,7 +129,7 @@ export async function finalAction(a:Action, bot_id:string){
console.log('=> BOT BROADCAST') console.log('=> BOT BROADCAST')
if (!content) throw 'no content' if (!content) throw 'no content'
if (!theChat) throw 'no chat' if (!theChat) throw 'no chat'
if (!theChat.type === constants.chat_types.tribe) throw 'not a tribe' if (theChat.type !== constants.chat_types.tribe) throw 'not a tribe'
const encryptedForMeText = rsa.encrypt(owner.contactKey, content) const encryptedForMeText = rsa.encrypt(owner.contactKey, content)
const encryptedText = rsa.encrypt(theChat.groupKey, content) const encryptedText = rsa.encrypt(theChat.groupKey, content)

7
src/controllers/bots.ts

@ -1,4 +1,3 @@
import * as path from 'path'
import * as tribes from '../utils/tribes' import * as tribes from '../utils/tribes'
import * as crypto from 'crypto' import * as crypto from 'crypto'
import { models } from '../models' import { models } from '../models'
@ -10,8 +9,7 @@ import * as socket from '../utils/socket'
import fetch from 'node-fetch' import fetch from 'node-fetch'
import * as SphinxBot from 'sphinx-bot' import * as SphinxBot from 'sphinx-bot'
import {Msg} from '../network/interfaces' import {Msg} from '../network/interfaces'
import constants from '../constants'
const constants = require(path.join(__dirname, '../../config/constants.json'))
export const getBots = async (req, res) => { export const getBots = async (req, res) => {
try { try {
@ -147,8 +145,7 @@ export async function keysendBotCmd(msg, b): Promise<boolean> {
export async function botKeysend(msg_type, bot_uuid, botmaker_pubkey, amount, chat_uuid:string, content?:string, sender_role?:number): Promise<boolean> { export async function botKeysend(msg_type, bot_uuid, botmaker_pubkey, amount, chat_uuid:string, content?:string, sender_role?:number): Promise<boolean> {
const owner = await models.Contact.findOne({ where: { isOwner: true } }) const owner = await models.Contact.findOne({ where: { isOwner: true } })
const dest = botmaker_pubkey const dest = botmaker_pubkey
const MIN_SATS = 3 const amt = Math.max(amount || constants.min_sat_amount)
const amt = Math.max(amount || MIN_SATS)
const opts = { const opts = {
amt, amt,
dest, dest,

4
src/controllers/chatTribes.ts

@ -6,12 +6,10 @@ import * as rsa from '../crypto/rsa'
import * as helpers from '../helpers' import * as helpers from '../helpers'
import * as socket from '../utils/socket' import * as socket from '../utils/socket'
import * as tribes from '../utils/tribes' import * as tribes from '../utils/tribes'
import * as path from 'path'
import { sendNotification } from '../hub' import { sendNotification } from '../hub'
import {personalizeMessage, decryptMessage} from '../utils/msg' import {personalizeMessage, decryptMessage} from '../utils/msg'
import { Op } from 'sequelize' import { Op } from 'sequelize'
import constants from '../constants'
const constants = require(path.join(__dirname,'../../config/constants.json'))
export async function joinTribe(req, res){ export async function joinTribe(req, res){
console.log('=> joinTribe') console.log('=> joinTribe')

6
src/controllers/chats.ts

@ -6,12 +6,10 @@ import * as network from '../network'
import * as socket from '../utils/socket' import * as socket from '../utils/socket'
import { sendNotification } from '../hub' import { sendNotification } from '../hub'
import * as md5 from 'md5' import * as md5 from 'md5'
import * as path from 'path'
import * as tribes from '../utils/tribes' import * as tribes from '../utils/tribes'
import * as timers from '../utils/timers' import * as timers from '../utils/timers'
import {replayChatHistory,createTribeChatParams,addPendingContactIdsToChat} from './chatTribes' import {replayChatHistory,createTribeChatParams,addPendingContactIdsToChat} from './chatTribes'
import constants from '../constants'
const constants = require(path.join(__dirname,'../../config/constants.json'))
export async function updateChat(req, res){ export async function updateChat(req, res){
console.log('=> updateChat') console.log('=> updateChat')
@ -149,7 +147,7 @@ export async function createGroupChat(req, res) {
} = req.body } = req.body
const contact_ids = req.body.contact_ids||[] const contact_ids = req.body.contact_ids||[]
const members: { [k: string]: {[k:string]:string} } = {} //{pubkey:{key,alias}, ...} const members: { [k: string]: {[k:string]:(string|number)} } = {} //{pubkey:{key,alias}, ...}
const owner = await models.Contact.findOne({ where: { isOwner: true } }) const owner = await models.Contact.findOne({ where: { isOwner: true } })
members[owner.publicKey] = { members[owner.publicKey] = {

7
src/controllers/confirmations.ts

@ -3,9 +3,7 @@ import { models } from '../models'
import * as socket from '../utils/socket' import * as socket from '../utils/socket'
import * as jsonUtils from '../utils/json' import * as jsonUtils from '../utils/json'
import * as network from '../network' import * as network from '../network'
import * as path from 'path' import constants from '../constants'
const constants = require(path.join(__dirname, '../../config/constants.json'))
export function sendConfirmation({ chat, sender, msg_id }) { export function sendConfirmation({ chat, sender, msg_id }) {
if (!msg_id) return if (!msg_id) return
@ -114,8 +112,7 @@ export async function receiveHeartbeat(payload) {
const owner = await models.Contact.findOne({ where: { isOwner: true } }) const owner = await models.Contact.findOne({ where: { isOwner: true } })
const amount = Math.round(receivedAmount/2) const amount = Math.round(receivedAmount/2)
const MIN_SATS = 3 const amt = Math.max(amount || constants.min_sat_amount)
const amt = Math.max(amount || MIN_SATS)
const opts = { const opts = {
amt, amt,
dest:sender_pub_key, dest:sender_pub_key,

4
src/controllers/contacts.ts

@ -5,10 +5,8 @@ import * as helpers from '../helpers'
import * as jsonUtils from '../utils/json' import * as jsonUtils from '../utils/json'
import {success, failure} from '../utils/res' import {success, failure} from '../utils/res'
import password from '../utils/password' import password from '../utils/password'
import * as path from 'path'
import { Op } from 'sequelize' import { Op } from 'sequelize'
import constants from '../constants'
const constants = require(path.join(__dirname,'../../config/constants.json'))
export const getContacts = async (req, res) => { export const getContacts = async (req, res) => {
const contacts = await models.Contact.findAll({ where:{deleted:false}, raw: true }) const contacts = await models.Contact.findAll({ where:{deleted:false}, raw: true })

3
src/controllers/index.ts

@ -14,13 +14,12 @@ import * as uploads from './uploads'
import * as confirmations from './confirmations' import * as confirmations from './confirmations'
import * as actions from './api' import * as actions from './api'
import {checkTag} from '../utils/gitinfo' import {checkTag} from '../utils/gitinfo'
import * as path from 'path'
import * as timers from '../utils/timers' import * as timers from '../utils/timers'
import * as builtInBots from '../builtin' import * as builtInBots from '../builtin'
import constants from '../constants'
const env = process.env.NODE_ENV || 'development'; const env = process.env.NODE_ENV || 'development';
console.log("=> env:",env) console.log("=> env:",env)
const constants = require(path.join(__dirname,'../../config/constants.json'))
export async function set(app) { export async function set(app) {

4
src/controllers/invoices.ts

@ -7,11 +7,9 @@ import * as helpers from '../helpers'
import { sendNotification } from '../hub' import { sendNotification } from '../hub'
import { success } from '../utils/res' import { success } from '../utils/res'
import {sendConfirmation} from './confirmations' import {sendConfirmation} from './confirmations'
import * as path from 'path'
import * as network from '../network' import * as network from '../network'
import * as short from 'short-uuid' import * as short from 'short-uuid'
import constants from '../constants'
const constants = require(path.join(__dirname,'../../config/constants.json'))
function stripLightningPrefix(s){ function stripLightningPrefix(s){
if(s.toLowerCase().startsWith('lightning:')) return s.substring(10) if(s.toLowerCase().startsWith('lightning:')) return s.substring(10)

2
src/controllers/media.ts

@ -16,10 +16,10 @@ import * as path from 'path'
import * as network from '../network' import * as network from '../network'
import * as meme from '../utils/meme' import * as meme from '../utils/meme'
import * as short from 'short-uuid' import * as short from 'short-uuid'
import constants from '../constants'
const env = process.env.NODE_ENV || 'development'; const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname,'../../config/app.json'))[env] const config = require(path.join(__dirname,'../../config/app.json'))[env]
const constants = require(path.join(__dirname,'../../config/constants.json'))
/* /*

8
src/controllers/messages.ts

@ -8,11 +8,9 @@ import * as helpers from '../helpers'
import { success } from '../utils/res' import { success } from '../utils/res'
import * as timers from '../utils/timers' import * as timers from '../utils/timers'
import {sendConfirmation} from './confirmations' import {sendConfirmation} from './confirmations'
import * as path from 'path'
import * as network from '../network' import * as network from '../network'
import * as short from 'short-uuid' import * as short from 'short-uuid'
import constants from '../constants'
const constants = require(path.join(__dirname,'../../config/constants.json'))
export const getMessages = async (req, res) => { export const getMessages = async (req, res) => {
const dateToReturn = req.query.date; const dateToReturn = req.query.date;
@ -93,11 +91,11 @@ export const getAllMessages = async (req, res) => {
const offset = (req.query.offset && parseInt(req.query.offset)) || 0 const offset = (req.query.offset && parseInt(req.query.offset)) || 0
console.log(`=> getAllMessages, limit: ${limit}, offset: ${offset}`) console.log(`=> getAllMessages, limit: ${limit}, offset: ${offset}`)
const messages = await models.Message.findAll({ order: [['chat_id', 'asc']], limit, offset }) const messages = await models.Message.findAll({ order: [['id', 'asc']], limit, offset })
console.log('=> got msgs',(messages&&messages.length)) console.log('=> got msgs',(messages&&messages.length))
const chatIds:number[] = [] const chatIds:number[] = []
messages.forEach((m) => { messages.forEach((m) => {
if(!chatIds.includes(m.chatId)) { if(m.chatId && !chatIds.includes(m.chatId)) {
chatIds.push(m.chatId) chatIds.push(m.chatId)
} }
}) })

65
src/controllers/payment.ts

@ -3,12 +3,12 @@ import { sendNotification } from '../hub'
import * as socket from '../utils/socket' import * as socket from '../utils/socket'
import * as jsonUtils from '../utils/json' import * as jsonUtils from '../utils/json'
import * as helpers from '../helpers' import * as helpers from '../helpers'
import { success } from '../utils/res' import { failure, success } from '../utils/res'
import * as lightning from '../utils/lightning'
import {tokenFromTerms} from '../utils/ldat' import {tokenFromTerms} from '../utils/ldat'
import * as constants from '../../config/constants.json'
import * as network from '../network' import * as network from '../network'
import * as short from 'short-uuid' import * as short from 'short-uuid'
import constants from '../constants'
import { Op } from 'sequelize'
export const sendPayment = async (req, res) => { export const sendPayment = async (req, res) => {
const { const {
@ -171,49 +171,26 @@ export const listPayments = async (req, res) => {
const limit = (req.query.limit && parseInt(req.query.limit)) || 100 const limit = (req.query.limit && parseInt(req.query.limit)) || 100
const offset = (req.query.offset && parseInt(req.query.offset)) || 0 const offset = (req.query.offset && parseInt(req.query.offset)) || 0
const payments: any[] = [] const MIN_VAL=constants.min_sat_amount
try {
const MIN_VAL=3 const msgs = await models.Message.findAll({
where:{
const invs:any = await lightning.listAllInvoices() type: {[Op.or]: [
if(invs && invs.length){ constants.message_types.payment,
invs.forEach(inv=>{ constants.message_types.direct_payment
const val = inv.value && parseInt(inv.value) ]},
if(val && val>MIN_VAL) { amount: {
let payment_hash='' [Op.gt]: MIN_VAL // greater than
if(inv.r_hash){
payment_hash = Buffer.from(inv.r_hash).toString('hex')
} }
payments.push({ },
type:'invoice', order: [['createdAt', 'desc']],
amount:parseInt(inv.value), limit,
date:parseInt(inv.creation_date), offset
payment_request:inv.payment_request,
payment_hash
})
}
})
}
const pays:any = await lightning.listAllPayments()
if(pays && pays.length){
pays.forEach(pay=>{
const val = pay.value && parseInt(pay.value)
if(val && val>MIN_VAL) {
payments.push({
type:'payment',
amount:parseInt(pay.value),
date:parseInt(pay.creation_date),
// pubkey:pay.path[pay.path.length-1],
payment_hash: pay.payment_hash,
})
}
}) })
const ret = msgs||[]
success(res, ret.map(message=> jsonUtils.messageToJson(message, null)))
} catch(e) {
failure(res, 'cant find payments')
} }
// latest one first
payments.sort((a,b)=> b.date - a.date)
success(res, payments.splice(offset, limit))
}; };

4
src/controllers/subscriptions.ts

@ -8,10 +8,8 @@ import * as jsonUtils from '../utils/json'
import * as helpers from '../helpers' import * as helpers from '../helpers'
import * as rsa from '../crypto/rsa' import * as rsa from '../crypto/rsa'
import * as moment from 'moment' import * as moment from 'moment'
import * as path from 'path'
import * as network from '../network' import * as network from '../network'
import constants from '../constants'
const constants = require(path.join(__dirname,'../../config/constants.json'))
// store all current running jobs in memory // store all current running jobs in memory
let jobs = {} let jobs = {}

42
src/grpc/index.ts

@ -6,9 +6,8 @@ import * as decodeUtils from '../utils/decode'
import {loadLightning} from '../utils/lightning' import {loadLightning} from '../utils/lightning'
import * as network from '../network' import * as network from '../network'
import * as moment from 'moment' import * as moment from 'moment'
import * as path from 'path' import constants from '../constants'
const constants = require(path.join(__dirname,'../../config/constants.json'))
const ERR_CODE_UNAVAILABLE = 14 const ERR_CODE_UNAVAILABLE = 14
const ERR_CODE_STREAM_REMOVED = 2 const ERR_CODE_STREAM_REMOVED = 2
@ -25,6 +24,19 @@ export function subscribeInvoices(parseKeysendInvoice) {
if(response.is_keysend) { if(response.is_keysend) {
parseKeysendInvoice(response) parseKeysendInvoice(response)
} else { } else {
let decodedPaymentRequest = decodeUtils.decode(response['payment_request']);
var paymentHash = "";
for (var i=0; i<decodedPaymentRequest["data"]["tags"].length; i++) {
let tag = decodedPaymentRequest["data"]["tags"][i];
if (tag['description'] == 'payment_hash') {
paymentHash = tag['value'];
break;
}
}
let settleDate = parseInt(response['settle_date'] + '000');
const invoice = await models.Message.findOne({ where: { type: constants.message_types.invoice, payment_request: response['payment_request'] } }) const invoice = await models.Message.findOne({ where: { type: constants.message_types.invoice, payment_request: response['payment_request'] } })
if (invoice == null) { if (invoice == null) {
// console.log("ERROR: Invoice " + response['payment_request'] + " not found"); // console.log("ERROR: Invoice " + response['payment_request'] + " not found");
@ -37,23 +49,23 @@ export function subscribeInvoices(parseKeysendInvoice) {
type: 'invoice_payment', type: 'invoice_payment',
response: {invoice: payReq} response: {invoice: payReq}
}) })
await models.Message.create({
chatId: 0,
type: constants.message_types.payment,
sender: 0,
amount: response['amt_paid_sat'],
amountMsat: response['amt_paid_msat'],
paymentHash: paymentHash,
date: new Date(settleDate),
messageContent: response['memo'],
status: constants.statuses.confirmed,
createdAt: new Date(settleDate),
updatedAt: new Date(settleDate)
})
return return
} }
models.Message.update({ status: constants.statuses.confirmed }, { where: { id: invoice.id } }) models.Message.update({ status: constants.statuses.confirmed }, { where: { id: invoice.id } })
let decodedPaymentRequest = decodeUtils.decode(response['payment_request']);
var paymentHash = "";
for (var i=0; i<decodedPaymentRequest["data"]["tags"].length; i++) {
let tag = decodedPaymentRequest["data"]["tags"][i];
if (tag['description'] == 'payment_hash') {
paymentHash = tag['value'];
break;
}
}
let settleDate = parseInt(response['settle_date'] + '000');
const chat = await models.Chat.findOne({ where: { id: invoice.chatId } }) const chat = await models.Chat.findOne({ where: { id: invoice.chatId } })
const contactIds = JSON.parse(chat.contactIds) const contactIds = JSON.parse(chat.contactIds)
const senderId = contactIds.find(id => id != invoice.sender) const senderId = contactIds.find(id => id != invoice.sender)

3
src/helpers.ts

@ -1,8 +1,7 @@
import { models } from './models' import { models } from './models'
import * as md5 from 'md5' import * as md5 from 'md5'
import * as network from './network' import * as network from './network'
import constants from './constants'
const constants = require('../config/constants.json');
export const findOrCreateChat = async (params) => { export const findOrCreateChat = async (params) => {
const { chat_id, owner_id, recipient_id } = params const { chat_id, owner_id, recipient_id } = params

2
src/hub.ts

@ -7,8 +7,8 @@ import * as helpers from './helpers'
import {nodeinfo} from './utils/nodeinfo' import {nodeinfo} from './utils/nodeinfo'
import { loadLightning } from './utils/lightning' import { loadLightning } from './utils/lightning'
import * as path from 'path' import * as path from 'path'
import constants from './constants'
const constants = require(path.join(__dirname, '../config/constants.json'))
const env = process.env.NODE_ENV || 'development'; const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname,'../config/app.json'))[env]; const config = require(path.join(__dirname,'../config/app.json'))[env];

4
src/network/intercept.ts

@ -2,10 +2,8 @@ import { Msg } from './interfaces'
import { models } from '../models' import { models } from '../models'
import { builtinBotEmit } from '../builtin' import { builtinBotEmit } from '../builtin'
import { keysendBotCmd, postToBotServer } from '../controllers/bots' import { keysendBotCmd, postToBotServer } from '../controllers/bots'
import * as path from 'path'
import * as SphinxBot from 'sphinx-bot' import * as SphinxBot from 'sphinx-bot'
import constants from '../constants'
const constants = require(path.join(__dirname, '../../config/constants.json'))
/* /*
default show or not default show or not

3
src/network/modify.ts

@ -1,4 +1,3 @@
import * as path from 'path'
import fetch from 'node-fetch' import fetch from 'node-fetch'
import {parseLDAT} from '../utils/ldat' import {parseLDAT} from '../utils/ldat'
import * as rsa from '../crypto/rsa' import * as rsa from '../crypto/rsa'
@ -9,8 +8,8 @@ import { models } from '../models'
import * as RNCryptor from 'jscryptor' import * as RNCryptor from 'jscryptor'
import {sendMessage} from './send' import {sendMessage} from './send'
// import { Op } from 'sequelize' // import { Op } from 'sequelize'
import constants from '../constants'
const constants = require(path.join(__dirname,'../../config/constants.json'))
const msgtypes = constants.message_types const msgtypes = constants.message_types
export async function modifyPayloadAndSaveMediaKey(payload, chat, sender) { export async function modifyPayloadAndSaveMediaKey(payload, chat, sender) {

31
src/network/receive.ts

@ -1,4 +1,3 @@
import * as path from 'path'
import * as lndService from '../grpc' import * as lndService from '../grpc'
import {getInfo} from '../utils/lightning' import {getInfo} from '../utils/lightning'
import {ACTIONS} from '../controllers' import {ACTIONS} from '../controllers'
@ -13,6 +12,8 @@ import { Op } from 'sequelize'
import * as timers from '../utils/timers' import * as timers from '../utils/timers'
import * as socket from '../utils/socket' import * as socket from '../utils/socket'
import { sendNotification } from '../hub' import { sendNotification } from '../hub'
import * as decodeUtils from '../utils/decode'
import constants from '../constants'
/* /*
delete type: delete type:
@ -20,7 +21,6 @@ owner needs to check that the delete is the one who made the msg
in receiveDeleteMessage check the deleter is og sender? in receiveDeleteMessage check the deleter is og sender?
*/ */
const constants = require(path.join(__dirname,'../../config/constants.json'))
const msgtypes = constants.message_types const msgtypes = constants.message_types
export const typesToForward=[ export const typesToForward=[
@ -250,6 +250,32 @@ async function parseAndVerifyPayload(data){
} }
} }
async function saveAnonymousKeysend(response) {
let decodedPaymentRequest = decodeUtils.decode(response['payment_request']);
var paymentHash = "";
for (var i=0; i<decodedPaymentRequest["data"]["tags"].length; i++) {
let tag = decodedPaymentRequest["data"]["tags"][i];
if (tag['description'] == 'payment_hash') {
paymentHash = tag['value'];
break;
}
}
let settleDate = parseInt(response['settle_date'] + '000');
await models.Message.create({
chatId: 0,
type: constants.message_types.direct_payment,
sender: 0,
amount: response['amt_paid_sat'],
amountMsat: response['amt_paid_msat'],
paymentHash: paymentHash,
date: new Date(settleDate),
messageContent: response['memo'],
status: constants.statuses.confirmed,
createdAt: new Date(settleDate),
updatedAt: new Date(settleDate)
})
}
export async function parseKeysendInvoice(i){ export async function parseKeysendInvoice(i){
const recs = i.htlcs && i.htlcs[0] && i.htlcs[0].custom_records const recs = i.htlcs && i.htlcs[0] && i.htlcs[0].custom_records
const buf = recs && recs[SPHINX_CUSTOM_RECORD_KEY] const buf = recs && recs[SPHINX_CUSTOM_RECORD_KEY]
@ -261,6 +287,7 @@ export async function parseKeysendInvoice(i){
response: {amount:value||0} response: {amount:value||0}
}) })
sendNotification(-1, '', 'keysend') sendNotification(-1, '', 'keysend')
saveAnonymousKeysend(i)
return return
} }

10
src/network/send.ts

@ -2,18 +2,14 @@ import { models } from '../models'
import * as LND from '../utils/lightning' import * as LND from '../utils/lightning'
import * as signer from '../utils/signer' import * as signer from '../utils/signer'
import {personalizeMessage, decryptMessage} from '../utils/msg' import {personalizeMessage, decryptMessage} from '../utils/msg'
import * as path from 'path'
import * as tribes from '../utils/tribes' import * as tribes from '../utils/tribes'
import {tribeOwnerAutoConfirmation} from '../controllers/confirmations' import {tribeOwnerAutoConfirmation} from '../controllers/confirmations'
import {typesToForward} from './receive' import {typesToForward} from './receive'
import * as intercept from './intercept' import * as intercept from './intercept'
import constants from '../constants'
const constants = require(path.join(__dirname,'../../config/constants.json'))
type NetworkType = undefined | 'mqtt' | 'lightning' type NetworkType = undefined | 'mqtt' | 'lightning'
const MIN_SATS = 3;
export async function sendMessage(params) { export async function sendMessage(params) {
const { type, chat, message, sender, amount, success, failure, skipPubKey, isForwarded } = params const { type, chat, message, sender, amount, success, failure, skipPubKey, isForwarded } = params
if(!chat || !sender) return if(!chat || !sender) return
@ -88,7 +84,7 @@ export async function sendMessage(params) {
let mqttTopic = networkType==='mqtt' ? `${destkey}/${chatUUID}` : '' let mqttTopic = networkType==='mqtt' ? `${destkey}/${chatUUID}` : ''
// sending a payment to one subscriber (like buying a pic) // sending a payment to one subscriber (like buying a pic)
if(isTribeOwner && contactIds.length===1 && amount && amount>MIN_SATS) { if(isTribeOwner && contactIds.length===1 && amount && amount>constants.min_sat_amount) {
mqttTopic = '' // FORCE KEYSEND!!! mqttTopic = '' // FORCE KEYSEND!!!
} }
@ -97,7 +93,7 @@ export async function sendMessage(params) {
const opts = { const opts = {
dest: destkey, dest: destkey,
data: m, data: m,
amt: Math.max((amount||0), MIN_SATS) amt: Math.max((amount||0), constants.min_sat_amount)
} }
try { try {

3
src/utils/msg.ts

@ -1,8 +1,7 @@
import { tokenFromTerms } from './ldat' import { tokenFromTerms } from './ldat'
import * as path from 'path'
import * as rsa from '../crypto/rsa' import * as rsa from '../crypto/rsa'
const constants = require(path.join(__dirname,'../../config/constants.json')) import constants from '../constants'
function addInRemoteText(full:{[k:string]:any}, contactId, isTribe:boolean){ function addInRemoteText(full:{[k:string]:any}, contactId, isTribe:boolean){
const m = full && full.message const m = full && full.message

4
src/utils/timers.ts

@ -1,8 +1,6 @@
import { models } from '../models' import { models } from '../models'
import * as network from '../network' import * as network from '../network'
import * as path from 'path' import constants from '../constants'
const constants = require(path.join(__dirname,'../../config/constants.json'))
const timerz={} const timerz={}
function clearTimer(t){ function clearTimer(t){

Loading…
Cancel
Save