fix: update versions

This commit is contained in:
Richard Ramos 2020-02-26 08:37:07 -04:00
parent 14edadc6e2
commit 9700d914be
12 changed files with 2730 additions and 3270 deletions

18
.eslintrc Normal file
View File

@ -0,0 +1,18 @@
{
"env": {
"node": true,
"browser": true,
"jest": true
},
"parser": "@typescript-eslint/parser",
"extends": [
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
],
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module"
},
"rules": {},
"overrides": []
}

View File

@ -1,290 +0,0 @@
{
"env": {
"browser": true,
"es6": true,
"node": true
},
"parser": "babel-eslint",
"extends": [
"eslint:recommended"
],
"parserOptions": {
"sourceType": "module",
"ecmaVersion": 2018,
"ecmaFeatures": {
"jsx": true
}
},
"globals": {
"__": true
},
"plugins": [
"react"
],
"rules": {
"accessor-pairs": "error",
"array-bracket-newline": "error",
"array-bracket-spacing": [
"error",
"never"
],
"array-callback-return": "off",
"array-element-newline": "off",
"arrow-body-style": "off",
"arrow-parens": "off",
"arrow-spacing": [
"error",
{
"after": true,
"before": true
}
],
"block-scoped-var": "error",
"block-spacing": "error",
"brace-style": "off",
"callback-return": "off",
"camelcase": "off",
"capitalized-comments": "off",
"class-methods-use-this": "off",
"comma-dangle": "error",
"comma-spacing": "off",
"comma-style": [
"error",
"last"
],
"complexity": "error",
"computed-property-spacing": [
"error",
"never"
],
"consistent-return": "off",
"consistent-this": "off",
"curly": "off",
"default-case": "error",
"dot-location": [
"error",
"property"
],
"dot-notation": "off",
"eol-last": "error",
"eqeqeq": "error",
"for-direction": "error",
"func-call-spacing": "error",
"func-name-matching": "error",
"func-names": "off",
"func-style": "off",
"function-paren-newline": "off",
"generator-star-spacing": "error",
"getter-return": "error",
"global-require": "off",
"guard-for-in": "off",
"handle-callback-err": "off",
"id-blacklist": "error",
"id-length": "off",
"id-match": "error",
"indent": "off",
"indent-legacy": "off",
"init-declarations": "off",
"jsx-quotes": "error",
"key-spacing": "off",
"keyword-spacing": "off",
"line-comment-position": "off",
"lines-around-comment": "error",
"lines-around-directive": "error",
"max-depth": "error",
"max-len": "off",
"max-lines": "off",
"max-params": "off",
"max-statements": "off",
"max-statements-per-line": "off",
"multiline-ternary": [
"error",
"never"
],
"new-parens": "off",
"newline-after-var": "off",
"newline-before-return": "off",
"newline-per-chained-call": "off",
"no-alert": "error",
"no-array-constructor": "error",
"no-await-in-loop": "error",
"no-bitwise": "error",
"no-buffer-constructor": "error",
"no-caller": "error",
"no-catch-shadow": "error",
"no-confusing-arrow": "error",
"no-console": "off",
"no-continue": "off",
"no-debugger": "warn",
"no-div-regex": "error",
"no-duplicate-imports": "error",
"no-else-return": 2,
"no-empty-function": "off",
"no-eq-null": "error",
"no-eval": "off",
"no-extend-native": "error",
"no-extra-bind": "error",
"no-extra-label": "error",
"no-extra-parens": "off",
"no-floating-decimal": "error",
"no-implicit-coercion": [
"error",
{
"allow": ["!!"]
}
],
"no-implicit-globals": "error",
"no-implied-eval": "error",
"no-inline-comments": "off",
"no-inner-declarations": [
"error",
"functions"
],
"no-invalid-this": "off",
"no-iterator": "error",
"no-label-var": "error",
"no-labels": "error",
"no-lone-blocks": "error",
"no-lonely-if": "off",
"no-loop-func": "off",
"no-magic-numbers": "off",
"no-mixed-operators": "error",
"no-mixed-requires": "error",
"no-multi-assign": "error",
"no-multi-spaces": "off",
"no-multi-str": "error",
"no-multiple-empty-lines": "error",
"no-native-reassign": "error",
"no-negated-condition": "off",
"no-negated-in-lhs": "error",
"no-nested-ternary": "error",
"no-new": "error",
"no-new-func": "error",
"no-new-object": "error",
"no-new-require": "error",
"no-new-wrappers": "error",
"no-octal-escape": "error",
"no-param-reassign": "off",
"no-path-concat": "error",
"no-plusplus": "off",
"no-process-env": "off",
"no-process-exit": "off",
"no-proto": "error",
"no-prototype-builtins": "off",
"no-restricted-globals": "error",
"no-restricted-imports": "error",
"no-restricted-modules": "error",
"no-restricted-properties": "error",
"no-restricted-syntax": "error",
"no-return-assign": "error",
"no-return-await": "error",
"no-script-url": "error",
"no-self-compare": "error",
"no-sequences": "error",
"no-shadow": "off",
"no-shadow-restricted-names": "error",
"no-spaced-func": "error",
"no-sync": "off",
"no-tabs": "error",
"no-template-curly-in-string": "error",
"no-ternary": "off",
"no-throw-literal": "error",
"no-trailing-spaces": "off",
"no-undef-init": "error",
"no-undefined": "off",
"no-underscore-dangle": "off",
"no-unmodified-loop-condition": "error",
"no-unneeded-ternary": "error",
"no-unused-expressions": "error",
"no-unused-vars": ["error", {
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_"
}],
"no-use-before-define": "off",
"no-useless-call": "off",
"no-useless-computed-key": "error",
"no-useless-concat": "error",
"no-useless-constructor": "error",
"no-useless-escape": "off",
"no-useless-rename": "error",
"no-useless-return": "off",
"no-var": "off",
"no-void": "error",
"no-warning-comments": "off",
"no-whitespace-before-property": "error",
"no-with": "error",
"nonblock-statement-body-position": "error",
"object-curly-newline": "off",
"object-curly-spacing": [
"off"
],
"object-property-newline": "off",
"object-shorthand": "off",
"one-var": "off",
"one-var-declaration-per-line": "off",
"operator-assignment": "off",
"operator-linebreak": "error",
"padded-blocks": "off",
"padding-line-between-statements": "error",
"prefer-arrow-callback": "off",
"prefer-const": "off",
"prefer-destructuring": "off",
"prefer-numeric-literals": "error",
"prefer-promise-reject-errors": "error",
"prefer-reflect": "off",
"prefer-rest-params": "off",
"prefer-spread": "off",
"prefer-template": "off",
"quote-props": "off",
"quotes": "off",
"radix": "error",
"require-await": "off",
"require-jsdoc": "off",
"rest-spread-spacing": "error",
"semi": "error",
"semi-spacing": [
"error",
{
"after": true,
"before": false
}
],
"semi-style": [
"error",
"last"
],
"sort-imports": "off",
"sort-keys": "off",
"sort-vars": "off",
"space-before-blocks": "off",
"space-before-function-paren": "off",
"space-in-parens": [
"error",
"never"
],
"space-infix-ops": "off",
"space-unary-ops": "error",
"spaced-comment": "off",
"strict": "error",
"switch-colon-spacing": "error",
"symbol-description": "error",
"template-curly-spacing": [
"error",
"never"
],
"template-tag-spacing": "error",
"unicode-bom": [
"error",
"never"
],
"valid-jsdoc": "error",
"vars-on-top": "off",
"wrap-iife": "error",
"wrap-regex": "error",
"yield-star-spacing": "error",
"yoda": [
"error",
"never"
]
}
}

12
.prettierrc Normal file
View File

@ -0,0 +1,12 @@
{
"trailingComma": "none",
"tabWidth": 2,
"semi": true,
"singleQuote": false,
"useTabs": false,
"jsxSingleQuote": false,
"bracketSpacing": false,
"jsxBracketSameLine": false,
"arrowParens": "avoid",
"printWidth": 120
}

View File

@ -1,45 +0,0 @@
/* global module */
module.exports = function (api) {
const node = {
ignore: [],
plugins: [
'babel-plugin-macros',
[
'@babel/plugin-proposal-decorators', {
legacy: true
}
],
'@babel/plugin-syntax-dynamic-import',
'babel-plugin-dynamic-import-node',
[
'@babel/plugin-proposal-class-properties', {
loose: true
}
],
'@babel/plugin-proposal-optional-chaining',
[
'@babel/plugin-transform-runtime', {
corejs: 2
}
]
],
presets: [
[
'@babel/preset-env', {
targets: {
node: '8.11.3'
}
}
],
'@babel/preset-typescript'
]
};
switch (api.env()) {
case 'node':
return node;
default:
throw new Error(`invalid babel env: ${api.env}`);
}
};

View File

@ -1,3 +0,0 @@
const StatusJS = require('./dist/index.js');
module.exports = StatusJS;

View File

@ -12,15 +12,12 @@
"build": "npm-run-all build:*",
"build:node": "npm run babel:node",
"clean": "rimraf dist",
"lint": "npm-run-all lint:*",
"lint:js": "ls",
"lint:ts": "tslint -c tslint.json 'src/**/*.ts'",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",
"prepublishOnly": "npm-run-all clean build",
"start": "run-p start:*",
"start:babel": "npm run babel:watch",
"start:type-check": "npm run type-check:watch",
"tsc": "tsc",
"tslint": "tslint",
"type-check": "tsc",
"type-check:watch": "npm run type-check -- --watch"
},
@ -35,43 +32,42 @@
},
"homepage": "https://github.com/status-im/status-js#readme",
"dependencies": {
"bip39": "^2.5.0",
"bourne": "^1.1.2",
"@hapi/bourne": "^2.0.0",
"chance": "^1.0.16",
"ethereum-hdwallet": "0.0.19",
"ethereumjs-util": "^6.0.0",
"transit-js": "0.8.861",
"web3": "1.0.0-beta.36"
"web3": "1.2.6"
},
"devDependencies": {
"@babel/cli": "^7.1.5",
"@babel/core": "^7.1.6",
"@babel/plugin-proposal-class-properties": "^7.1.0",
"@babel/plugin-proposal-decorators": "^7.1.6",
"@babel/plugin-proposal-object-rest-spread": "^7.0.0",
"@babel/plugin-proposal-optional-chaining": "^7.0.0",
"@babel/plugin-syntax-dynamic-import": "^7.0.0",
"@babel/plugin-transform-destructuring": "^7.1.3",
"@babel/plugin-transform-flow-strip-types": "^7.1.6",
"@babel/plugin-transform-runtime": "^7.1.0",
"@babel/preset-env": "^7.1.6",
"@babel/preset-react": "^7.0.0",
"@babel/preset-typescript": "^7.1.0",
"@babel/runtime-corejs2": "^7.1.5",
"@types/web3": "^1.0.12",
"babel-eslint": "^10.0.1",
"babel-loader": "^8.0.4",
"babel-plugin-dynamic-import-node": "^2.2.0",
"babel-plugin-macros": "^2.4.2",
"babel-plugin-module-resolver": "^3.1.1",
"babel-plugin-transform-react-remove-prop-types": "^0.4.20",
"cross-env": "^5.2.0",
"eslint": "^5.9.0",
"@babel/cli": "^7.8.4",
"@babel/core": "^7.8.4",
"@babel/plugin-proposal-class-properties": "^7.8.3",
"@babel/plugin-proposal-decorators": "^7.8.3",
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.8.3",
"@babel/plugin-proposal-object-rest-spread": "^7.8.3",
"@babel/plugin-proposal-optional-chaining": "^7.8.3",
"@babel/plugin-proposal-private-methods": "^7.8.3",
"@babel/plugin-syntax-dynamic-import": "^7.8.3",
"@babel/plugin-transform-destructuring": "^7.8.3",
"@babel/plugin-transform-flow-strip-types": "^7.8.3",
"@babel/plugin-transform-runtime": "^7.8.3",
"@babel/preset-env": "^7.8.4",
"@babel/preset-typescript": "^7.8.3",
"@typescript-eslint/eslint-plugin": "^2.21.0",
"@typescript-eslint/parser": "^2.21.0",
"babel-eslint": "^10.0.3",
"babel-loader": "^8.0.6",
"babel-plugin-dynamic-import-node": "^2.3.0",
"babel-plugin-macros": "^2.8.0",
"babel-plugin-module-resolver": "^4.0.0",
"cross-env": "^7.0.0",
"eslint": "^6.8.0",
"eslint-plugin-babel": "^5.3.0",
"eslint-plugin-import": "^2.20.1",
"eslint-plugin-standard": "^4.0.1",
"npm-run-all": "^4.1.5",
"rimraf": "^2.6.2",
"source-map-support": "^0.5.10",
"rimraf": "^3.0.2",
"source-map-support": "^0.5.16",
"tape-async": "^2.3.0",
"tslint": "^5.11.0",
"typescript": "^3.2.1"
"typescript": "^3.8.2"
}
}

View File

@ -1,27 +1,27 @@
enum Topics {
CONTACT_DISCOVERY_TOPIC = "0xf8946aac",
CONTACT_DISCOVERY_TOPIC = "0xf8946aac"
}
export default {
messageTags: {
contactRequest: "c2",
message: "c4",
message: "c4"
},
messageTypes: {
GROUP_MESSAGE: "public-group-user-message",
USER_MESSAGE: "user-message",
USER_MESSAGE: "user-message"
},
post: {
POW_TARGET: 0.002,
POW_TIME: 1,
TTL: 10,
TTL: 10
},
regExp: {
CONTACT_CODE_REGEXP: /^(0x)?[0-9a-f]{130}$/i,
CONTACT_CODE_REGEXP: /^(0x)?[0-9a-f]{130}$/i
},
contentType: {
JSON: "content/json",
TEXT: "text/plain"
},
topics: Topics,
topics: Topics
};

View File

@ -2,11 +2,12 @@ import web3Lib from "web3";
import utils from "./utils.js";
import mailservers from "./mailservers";
import constants from "./constants";
import Bourne from "bourne";
import transit from "transit-js";
declare global {
interface Window { web3: any; }
interface Window {
web3: any;
}
}
if (typeof window !== "undefined") {
@ -20,7 +21,7 @@ class Message {
public clockValue: number;
public timestamp: number;
constructor(content: string, contentType: string, messageType: string, clockValue: number, timestamp: number){
constructor(content: string, contentType: string, messageType: string, clockValue: number, timestamp: number) {
this.content = content;
this.contentType = contentType;
this.messageType = messageType;
@ -30,22 +31,30 @@ class Message {
}
const mh = transit.makeWriteHandler({
tag: function() { return constants.messageTags.message; },
rep: function(v) { return [v.content, v.contentType, transit.keyword(v.messageType), v.clockValue, v.timestamp]; },
stringRep: function() { return null; }
})
tag: function() {
return constants.messageTags.message;
},
rep: function(v) {
return [v.content, v.contentType, transit.keyword(v.messageType), v.clockValue, v.timestamp];
},
stringRep: function() {
return null;
}
});
const Web3 = typeof window !== "undefined" && window.web3 ? new web3Lib(window.web3.currentProvider) : web3Lib;
const { utils: { stringToHex, hexToUtf8 } } = Web3;
const {
utils: {stringToHex, hexToUtf8}
} = Web3;
// TODO: create a transit-js reader
const reader = transit.reader("json");
const writer = transit.writer("json", {
"handlers": transit.map([Message, mh])
handlers: transit.map([Message, mh])
});
function createStatusPayload(content: any, messageType: string, clockValue: number, contentType: string) {
const oneMonthInMs: number = 60 * 60 * 24 * 31 * 1000;
if (clockValue < (new Date().getTime())) {
if (clockValue < new Date().getTime()) {
clockValue = (new Date().getTime() + oneMonthInMs) * 100;
}
@ -76,7 +85,7 @@ class StatusJS {
this.isHttpProvider = false;
}
public async connect(url: string, privateKey?: string) {
public async connect(url: string, privateKey?: string): Promise<void> {
const web3: any = new web3Lib();
if (url.startsWith("ws://")) {
web3.setProvider(new Web3.providers.WebsocketProvider(url, {headers: {Origin: "statusjs"}}));
@ -93,40 +102,34 @@ class StatusJS {
this.mailservers = new mailservers(web3);
await web3.shh.setMinPoW(constants.post.POW_TARGET);
sig.set(
this,
privateKey ? await this.generateWhisperKeyFromWallet(privateKey) : await web3.shh.newKeyPair(),
);
sig.set(this, privateKey ? await this.generateWhisperKeyFromWallet(privateKey) : await web3.shh.newKeyPair());
}
public async connectToProvider(provider: any, privateKey: any) {
public async connectToProvider(provider: any, privateKey: any): Promise<void> {
const web3: any = new web3Lib(provider);
this.shh = web3.shh;
this.mailservers = new mailservers(web3);
await web3.shh.setMinPoW(constants.post.POW_TARGET);
sig.set(
this,
privateKey ? await this.generateWhisperKeyFromWallet(privateKey) : await web3.shh.newKeyPair(),
);
sig.set(this, privateKey ? await this.generateWhisperKeyFromWallet(privateKey) : await web3.shh.newKeyPair());
}
public isConnected() {
public isConnected(): boolean {
return this.shh.isListening();
}
private async generateWhisperKeyFromWallet(key: string) {
private async generateWhisperKeyFromWallet(key: string): Promise<string> {
const keyId = await this.shh.addPrivateKey(key);
return keyId;
}
public async getPublicKey() {
public async getPublicKey(): Promise<string> {
const pubKey = await this.shh.getPublicKey(sig.get(this));
return pubKey;
}
public async getUserName(pubKey?: any) {
public async getUserName(pubKey?: any): Promise<string> {
if (!pubKey) {
pubKey = await this.getPublicKey();
}
@ -134,12 +137,12 @@ class StatusJS {
return utils.generateUsernameFromSeed(pubKey);
}
private cleanChannelName(c: string) {
if(c.startsWith('#')) return c.substr(1);
private cleanChannelName(c: string): string {
if (c.startsWith("#")) return c.substr(1);
return c;
}
public async joinChat(channelName: string, cb?: any) {
public async joinChat(channelName: string, cb?: any): Promise<void> {
channelName = this.cleanChannelName(channelName);
const channelKey = await this.shh.generateSymKeyFromPassword(channelName);
@ -147,47 +150,46 @@ class StatusJS {
channelCode: Web3.utils.sha3(channelName).slice(0, 10),
channelKey,
channelName,
lastClockValue: 0,
lastClockValue: 0
};
if (cb) {
cb();
}
}
public async addContact(contactCode: string, cb?: any) {
public async addContact(contactCode: string, cb?: any): Promise<void> {
this.contacts[contactCode] = {
lastClockValue: 0,
username: utils.generateUsernameFromSeed(contactCode),
username: utils.generateUsernameFromSeed(contactCode)
};
if (cb) {
cb();
}
}
public leaveChat(channelName: string) {
public leaveChat(channelName: string): void {
channelName = this.cleanChannelName(channelName);
if (!this.isHttpProvider) {
this.channels[channelName].subscription.unsubscribe();
} else {
this.shh.deleteMessageFilter(this.channels[channelName].filterId)
.then(() => {
clearInterval(this.channels[channelName].interval);
});
this.shh.deleteMessageFilter(this.channels[channelName].filterId).then(() => {
clearInterval(this.channels[channelName].interval);
});
}
delete this.channels[channelName];
}
public async removeContact(contactCode: string) {
public async removeContact(contactCode: string): void {
delete this.contacts[contactCode];
}
public isSubscribedTo(channelName: string) {
public isSubscribedTo(channelName: string): boolean {
channelName = this.cleanChannelName(channelName);
return !!this.channels[channelName];
}
public onMessage(par1: any, par2: any) {
public onMessage(par1: any, par2: any): void {
if (typeof par1 === "function") {
this.onUserMessage(par1);
} else {
@ -195,11 +197,11 @@ class StatusJS {
}
}
public onContactRequest(cb: any) {
public onContactRequest(cb: any): void {
this.contactRequestCb = cb;
}
public onChannelMessage(channelName: string, cb: any) {
public onChannelMessage(channelName: string, cb: any): void {
channelName = this.cleanChannelName(channelName);
if (!this.channels[channelName]) {
@ -209,10 +211,10 @@ class StatusJS {
const filters = {
allowP2P: true,
symKeyID: this.channels[channelName].channelKey,
topics: [this.channels[channelName].channelCode],
topics: [this.channels[channelName].channelCode]
};
const messageHandler = (data: any) => {
const messageHandler = (data: any): void => {
try {
const username = utils.generateUsernameFromSeed(data.sig);
const payload = reader.read(hexToUtf8(data.payload));
@ -220,42 +222,51 @@ class StatusJS {
if (this.channels[channelName].lastClockValue < clockValue) {
this.channels[channelName].lastClockValue = clockValue;
}
cb(null, {payload: [payload.rep[0], payload.rep[1], payload.rep[2]._name, payload.rep[3], payload.rep[4]], data, username});
cb(null, {
payload: [payload.rep[0], payload.rep[1], payload.rep[2]._name, payload.rep[3], payload.rep[4]],
data,
username
});
} catch (err) {
cb("Discarding invalid message received");
}
};
if (this.isHttpProvider) {
this.shh.newMessageFilter(filters)
.then((filterId: any) => {
this.shh.newMessageFilter(filters).then((filterId: any) => {
this.channels[channelName].filterId = filterId;
this.channels[channelName].interval = setInterval(() => {
this.shh.getFilterMessages(filterId)
.then((data: any) => {
data.map((d: any) => {
messageHandler(d);
this.shh
.getFilterMessages(filterId)
.then((data: any) => {
data.map((d: any) => {
messageHandler(d);
});
})
.catch((err: any) => {
cb(err);
});
})
.catch((err: any) => { cb(err); });
}, 250);
});
} else {
this.channels[channelName].subscription = this.shh.subscribe("messages", filters)
.on("data", messageHandler)
.on("error", (err: any) => { cb(err); });
this.channels[channelName].subscription = this.shh
.subscribe("messages", filters)
.on("data", messageHandler)
.on("error", (err: any) => {
cb(err);
});
}
}
public onUserMessage(cb: any) {
public onUserMessage(cb: any): void {
const filters = {
allowP2P: true,
minPow: 0,
privateKeyID: sig.get(this),
topics: [constants.topics.CONTACT_DISCOVERY_TOPIC],
topics: [constants.topics.CONTACT_DISCOVERY_TOPIC]
};
const messageHandler = (data: any) => {
const messageHandler = (data: any): void => {
if (!this.contacts[data.sig]) {
this.addContact(data.sig);
}
@ -269,7 +280,11 @@ class StatusJS {
}
if (tag === constants.messageTags.message) {
cb(null, {payload: [payload.rep[0], payload.rep[1], payload.rep[2]._name, payload.rep[3], payload.rep[4]], data, username: this.contacts[data.sig].username});
cb(null, {
payload: [payload.rep[0], payload.rep[1], payload.rep[2]._name, payload.rep[3], payload.rep[4]],
data,
username: this.contacts[data.sig].username
});
} else if (tag === constants.messageTags.contactRequest) {
this.contacts[data.sig].displayName = payload.rep[0];
this.contacts[data.sig].profilePic = payload.rep[1];
@ -278,7 +293,7 @@ class StatusJS {
this.contactRequestCb(null, {
displayName: this.contacts[data.sig].displayName,
profilePic: this.contacts[data.sig].profilePic,
username: this.contacts[data.sig].username,
username: this.contacts[data.sig].username
});
}
}
@ -288,56 +303,70 @@ class StatusJS {
};
if (this.isHttpProvider) {
this.shh.newMessageFilter(filters)
.then((filterId: any) => {
this.shh.newMessageFilter(filters).then((filterId: any) => {
this.userMessagesSubscription = {};
this.userMessagesSubscription.filterId = filterId;
this.userMessagesSubscription.interval = setInterval(() => {
this.shh.getFilterMessages(filterId)
.then((data: any) => {
data.map((d: any) => {
messageHandler(d);
this.shh
.getFilterMessages(filterId)
.then((data: any) => {
data.map((d: any) => {
messageHandler(d);
});
})
.catch((err: any) => {
cb(err);
});
})
.catch((err: any) => { cb(err); });
}, 250);
});
} else {
this.userMessagesSubscription = this.shh.subscribe("messages", filters)
.on("data", (data: any) => { messageHandler(data); })
.on("error", (err: any) => { cb(err); });
this.userMessagesSubscription = this.shh
.subscribe("messages", filters)
.on("data", (data: any) => {
messageHandler(data);
})
.on("error", (err: any) => {
cb(err);
});
}
}
public sendUserMessage(contactCode: string, msg: string, cb?: any) {
public sendUserMessage(contactCode: string, msg: string, cb?: any): void {
if (!this.contacts[contactCode]) {
this.addContact(contactCode);
}
this.contacts[contactCode].lastClockValue++;
this.shh.post({
payload: createStatusPayload(msg, constants.messageTypes.USER_MESSAGE, this.contacts[contactCode].lastClockValue,
constants.contentType.TEXT),
powTarget: constants.post.POW_TARGET,
powTime: constants.post.POW_TIME,
pubKey: contactCode,
sig: sig.get(this),
topic: constants.topics.CONTACT_DISCOVERY_TOPIC,
ttl: constants.post.TTL,
}).then(() => {
if (!cb) {
return;
}
cb(null, true);
}).catch((e: any) => {
if (!cb) {
return;
}
cb(e, false);
});
this.shh
.post({
payload: createStatusPayload(
msg,
constants.messageTypes.USER_MESSAGE,
this.contacts[contactCode].lastClockValue,
constants.contentType.TEXT
),
powTarget: constants.post.POW_TARGET,
powTime: constants.post.POW_TIME,
pubKey: contactCode,
sig: sig.get(this),
topic: constants.topics.CONTACT_DISCOVERY_TOPIC,
ttl: constants.post.TTL
})
.then(() => {
if (!cb) {
return;
}
cb(null, true);
})
.catch((e: any) => {
if (!cb) {
return;
}
cb(e, false);
});
}
public sendGroupMessage(channelName: string, msg: string, cb?: any) {
public sendGroupMessage(channelName: string, msg: string, cb?: any): void {
channelName = this.cleanChannelName(channelName);
if (!this.channels[channelName]) {
if (!cb) {
@ -348,82 +377,103 @@ class StatusJS {
this.channels[channelName].lastClockValue++;
this.shh.post({
payload: createStatusPayload(msg, constants.messageTypes.GROUP_MESSAGE, this.channels[channelName].lastClockValue,
constants.contentType.TEXT),
powTarget: constants.post.POW_TARGET,
powTime: constants.post.POW_TIME,
sig: sig.get(this),
symKeyID: this.channels[channelName].channelKey,
topic: this.channels[channelName].channelCode,
ttl: constants.post.TTL,
}).then(() => {
if (!cb) {
return;
}
cb(null, true);
}).catch((e: any) => {
if (!cb) {
return;
}
cb(e, false);
});
this.shh
.post({
payload: createStatusPayload(
msg,
constants.messageTypes.GROUP_MESSAGE,
this.channels[channelName].lastClockValue,
constants.contentType.TEXT
),
powTarget: constants.post.POW_TARGET,
powTime: constants.post.POW_TIME,
sig: sig.get(this),
symKeyID: this.channels[channelName].channelKey,
topic: this.channels[channelName].channelCode,
ttl: constants.post.TTL
})
.then(() => {
if (!cb) {
return;
}
cb(null, true);
})
.catch((e: any) => {
if (!cb) {
return;
}
cb(e, false);
});
}
public sendJsonMessage(destination: string, msg: string, cb?: any) {
public sendJsonMessage(destination: string, msg: string, cb?: any): void {
if (constants.regExp.CONTACT_CODE_REGEXP.test(destination)) {
if (!this.contacts[destination]) {
this.addContact(destination);
}
this.contacts[destination].lastClockValue++;
this.shh.post({
payload: createStatusPayload(msg, constants.messageTypes.USER_MESSAGE, this.contacts[destination].lastClockValue,
constants.contentType.JSON),
powTarget: constants.post.POW_TARGET,
powTime: constants.post.POW_TIME,
pubKey: destination,
sig: sig.get(this),
topic: constants.topics.CONTACT_DISCOVERY_TOPIC,
ttl: constants.post.TTL,
}).then(() => {
if (!cb) {
return;
}
cb(null, true);
}).catch((e: any) => {
if (!cb) {
return;
}
cb(e, false);
});
this.shh
.post({
payload: createStatusPayload(
msg,
constants.messageTypes.USER_MESSAGE,
this.contacts[destination].lastClockValue,
constants.contentType.JSON
),
powTarget: constants.post.POW_TARGET,
powTime: constants.post.POW_TIME,
pubKey: destination,
sig: sig.get(this),
topic: constants.topics.CONTACT_DISCOVERY_TOPIC,
ttl: constants.post.TTL
})
.then(() => {
if (!cb) {
return;
}
cb(null, true);
})
.catch((e: any) => {
if (!cb) {
return;
}
cb(e, false);
});
} else {
this.channels[destination].lastClockValue++;
this.shh.post({
payload: createStatusPayload(JSON.stringify(msg), constants.messageTypes.GROUP_MESSAGE,
this.channels[destination].lastClockValue, constants.contentType.JSON),
powTarget: constants.post.POW_TARGET,
powTime: constants.post.POW_TIME,
sig: sig.get(this),
symKeyID: this.channels[destination].channelKey,
topic: this.channels[destination].channelCode,
ttl: constants.post.TTL,
}).then(() => {
if (!cb) {
return;
}
cb(null, true);
}).catch((e: any) => {
if (!cb) {
return;
}
cb(e, false);
});
this.shh
.post({
payload: createStatusPayload(
JSON.stringify(msg),
constants.messageTypes.GROUP_MESSAGE,
this.channels[destination].lastClockValue,
constants.contentType.JSON
),
powTarget: constants.post.POW_TARGET,
powTime: constants.post.POW_TIME,
sig: sig.get(this),
symKeyID: this.channels[destination].channelKey,
topic: this.channels[destination].channelCode,
ttl: constants.post.TTL
})
.then(() => {
if (!cb) {
return;
}
cb(null, true);
})
.catch((e: any) => {
if (!cb) {
return;
}
cb(e, false);
});
}
}
public sendMessage(destination: string, msg: string, cb?: any) {
public sendMessage(destination: string, msg: string, cb?: any): void {
if (constants.regExp.CONTACT_CODE_REGEXP.test(destination)) {
this.sendUserMessage(destination, msg, cb);
} else {
@ -431,32 +481,39 @@ class StatusJS {
}
}
public sendContent(contactCode: string, content: any, contentType: string, cb?: any) {
public sendContent(contactCode: string, content: any, contentType: string, cb?: any): void {
if (!this.contacts[contactCode]) {
this.addContact(contactCode);
}
this.contacts[contactCode].lastClockValue++;
this.shh.post({
payload: createStatusPayload(content, constants.messageTypes.USER_MESSAGE, this.contacts[contactCode].lastClockValue,
contentType),
powTarget: constants.post.POW_TARGET,
powTime: constants.post.POW_TIME,
pubKey: contactCode,
sig: sig.get(this),
topic: constants.topics.CONTACT_DISCOVERY_TOPIC,
ttl: constants.post.TTL,
}).then(() => {
if (!cb) {
return;
}
cb(null, true);
}).catch((e: any) => {
if (!cb) {
return;
}
cb(e, false);
});
this.shh
.post({
payload: createStatusPayload(
content,
constants.messageTypes.USER_MESSAGE,
this.contacts[contactCode].lastClockValue,
contentType
),
powTarget: constants.post.POW_TARGET,
powTime: constants.post.POW_TIME,
pubKey: contactCode,
sig: sig.get(this),
topic: constants.topics.CONTACT_DISCOVERY_TOPIC,
ttl: constants.post.TTL
})
.then(() => {
if (!cb) {
return;
}
cb(null, true);
})
.catch((e: any) => {
if (!cb) {
return;
}
cb(e, false);
});
}
}

View File

@ -4,68 +4,71 @@ const Topics = constants.topics;
class MailServers {
private web3: any;
private mailserver: string = "";
private bridgePeerId: string = "";
private symKeyID: string = "";
private mailserver = "";
private bridgePeerId = "";
private symKeyID = "";
constructor(web3: any) {
this.web3 = web3;
}
public async useMailserver(enode: string, cb?: any) {
public async useMailserver(enode: string, cb?: any): Promise<void> {
this.symKeyID = await this.web3.shh.generateSymKeyFromPassword("status-offline-inbox");
this.web3.currentProvider.send({
id: new Date().getTime(),
jsonrpc: "2.0",
method: "admin_addPeer",
params: [enode],
},
(err: any, res: any) => {
if (err) {
if (cb) {
return cb(err, false);
}
return;
}
if (!res.result) {
if (cb) {
return cb(err, false);
}
return;
}
setTimeout(() => {
this.web3.shh.markTrustedPeer(enode)
.then(() => {
this.mailserver = enode;
if (!cb) {
return true;
this.web3.currentProvider.send(
{
id: new Date().getTime(),
jsonrpc: "2.0",
method: "admin_addPeer",
params: [enode]
},
(err: any, res: any) => {
if (err) {
if (cb) {
return cb(err, false);
}
cb(null, true);
}).catch((e?: any) => {
if (!cb) {
return;
return;
}
if (!res.result) {
if (cb) {
return cb(err, false);
}
cb(e, false);
});
}, 1000);
});
return;
}
setTimeout(() => {
this.web3.shh
.markTrustedPeer(enode)
.then(() => {
this.mailserver = enode;
if (!cb) {
return true;
}
cb(null, true);
})
.catch((e?: any) => {
if (!cb) {
return;
}
cb(e, false);
});
}, 1000);
}
);
}
public async bridgeMailserver(enode: string, bridgePeerId: string, cb?: any){
public async bridgeMailserver(enode: string, bridgePeerId: string, cb?: any): Promise<void> {
await this.web3.shh.markTrustedPeer("libp2p:" + bridgePeerId);
this.bridgePeerId = bridgePeerId;
this.useMailserver(enode, cb);
}
public async requestUserMessages(options: any, cb?: any) {
public async requestUserMessages(options: any, cb?: any): Promise<void> {
await this.requestChannelMessages(constants.topics.CONTACT_DISCOVERY_TOPIC, options, cb);
}
public async requestChannelMessages(topic: string, options: any, cb?: any) {
public async requestChannelMessages(topic: string, options: any, cb?: any): Promise<void> {
if (this.mailserver === "") {
if (!cb) {
return;
@ -73,7 +76,7 @@ class MailServers {
return cb("Mailserver is not set", false);
}
const topics = [ topic.slice(0, 2) === "0x" ? topic : this.web3.utils.sha3(topic).slice(0, 10)];
const topics = [topic.slice(0, 2) === "0x" ? topic : this.web3.utils.sha3(topic).slice(0, 10)];
const mailserverPeer = this.mailserver;
@ -82,8 +85,8 @@ class MailServers {
const from = options.from || 0; // unix timestamp
const to = options.to || 0;
const limit = options.limit || 0;
const bridgePeerId = this.bridgePeerId ? this.bridgePeerId: null;
const bridgePeerId = this.bridgePeerId ? this.bridgePeerId : null;
let paramObj = {
from,
limit,
@ -94,29 +97,31 @@ class MailServers {
topics
};
if(bridgePeerId) {
if (bridgePeerId) {
paramObj = Object.assign(paramObj, {bridgePeerId});
}
this.web3.currentProvider.send({
id: new Date().getTime(),
jsonrpc: "2.0",
method: "shhext_requestMessages",
params: [paramObj],
},
(err?: any, res?: any) => {
if (err) {
if (cb) {
return cb(err);
this.web3.currentProvider.send(
{
id: new Date().getTime(),
jsonrpc: "2.0",
method: "shhext_requestMessages",
params: [paramObj]
},
(err?: any, res?: any) => {
if (err) {
if (cb) {
return cb(err);
}
return false;
}
return false;
}
if (cb) {
return cb(null, true);
if (cb) {
return cb(null, true);
}
return true;
}
return true;
});
);
}
}

View File

@ -2,14 +2,14 @@ import Chance from "chance";
import adjectives from "./data/adjectives.json";
import animals from "./data/animals.json";
function generateUsernameFromSeed(seed: string) {
function generateUsernameFromSeed(seed: string): string{
const chance = new Chance(seed);
const index1 = chance.integer({min: 0, max: adjectives.length - 1});
const index2 = chance.integer({min: 0, max: adjectives.length - 1});
const index3 = chance.integer({min: 0, max: animals.length - 1});
return [adjectives[index1], adjectives[index2], animals[index3]].map((u) => u[0].toUpperCase() + u.slice(1)).join(" ");
return [adjectives[index1], adjectives[index2], animals[index3]].map(u => u[0].toUpperCase() + u.slice(1)).join(" ");
}
export default {
generateUsernameFromSeed,
generateUsernameFromSeed
};

4
test/.eslintignore Normal file
View File

@ -0,0 +1,4 @@
node_modules
dist
coverage
examples

5004
yarn.lock

File diff suppressed because it is too large Load Diff