types-etc

pull/1199/head
Vincent 5 years ago
parent 78b1ef4805
commit f72423c2ba

@ -32,7 +32,6 @@ describe('Settings', function() {
app = await common.startAndStub(appProps); app = await common.startAndStub(appProps);
}); });
after(async () => { after(async () => {
await common.stopApp(app); await common.stopApp(app);
await common.killallElectron(); await common.killallElectron();

@ -3,6 +3,7 @@ interface ConversationAttributes {
left: boolean; left: boolean;
expireTimer: number; expireTimer: number;
profileSharing: boolean; profileSharing: boolean;
secondaryStatus: boolean;
mentionedUs: boolean; mentionedUs: boolean;
unreadCount: number; unreadCount: number;
isArchived: boolean; isArchived: boolean;

@ -1,7 +1,7 @@
import { ConversationType } from '../../ts/state/ducks/conversations'; import { ConversationType } from '../../ts/state/ducks/conversations';
import { Mesasge } from '../../ts/types/Message'; import { Mesasge } from '../../ts/types/Message';
type IdentityKey = { export type IdentityKey = {
id: string; id: string;
publicKey: ArrayBuffer; publicKey: ArrayBuffer;
firstUse: boolean; firstUse: boolean;
@ -9,14 +9,14 @@ type IdentityKey = {
nonblockingApproval: boolean; nonblockingApproval: boolean;
}; };
type PreKey = { export type PreKey = {
id: number; id: number;
publicKey: ArrayBuffer; publicKey: ArrayBuffer;
privateKey: ArrayBuffer; privateKey: ArrayBuffer;
recipient: string; recipient: string;
}; };
type SignedPreKey = { export type SignedPreKey = {
id: number; id: number;
publicKey: ArrayBuffer; publicKey: ArrayBuffer;
privateKey: ArrayBuffer; privateKey: ArrayBuffer;
@ -25,14 +25,14 @@ type SignedPreKey = {
signature: ArrayBuffer; signature: ArrayBuffer;
}; };
type ContactPreKey = { export type ContactPreKey = {
id: number; id: number;
identityKeyString: string; identityKeyString: string;
publicKey: ArrayBuffer; publicKey: ArrayBuffer;
keyId: number; keyId: number;
}; };
type ContactSignedPreKey = { export type ContactSignedPreKey = {
id: number; id: number;
identityKeyString: string; identityKeyString: string;
publicKey: ArrayBuffer; publicKey: ArrayBuffer;
@ -42,18 +42,18 @@ type ContactSignedPreKey = {
confirmed: boolean; confirmed: boolean;
}; };
type PairingAuthorisation = { export type PairingAuthorisation = {
primaryDevicePubKey: string; primaryDevicePubKey: string;
secondaryDevicePubKey: string; secondaryDevicePubKey: string;
requestSignature: ArrayBuffer; requestSignature: ArrayBuffer;
grantSignature?: ArrayBuffer; grantSignature?: ArrayBuffer;
}; };
type GuardNode = { export type GuardNode = {
ed25519PubKey: string; ed25519PubKey: string;
}; };
type SwarmNode = { export type SwarmNode = {
address: string; address: string;
ip: string; ip: string;
port: string; port: string;
@ -61,19 +61,19 @@ type SwarmNode = {
pubkey_x25519: string; pubkey_x25519: string;
}; };
type StorageItem = { export type StorageItem = {
id: string; id: string;
value: any; value: any;
}; };
type SessionDataInfo = { export type SessionDataInfo = {
id: string; id: string;
number: string; number: string;
deviceId: number; deviceId: number;
record: string; record: string;
}; };
type ServerToken = { export type ServerToken = {
serverUrl: string; serverUrl: string;
token: string; token: string;
}; };
@ -233,7 +233,7 @@ export function saveSeenMessageHash(data: {
hash: string; hash: string;
}): Promise<void>; }): Promise<void>;
// TODO: Strictly type the following // TODO: Strictly export type the following
export function updateLastHash(data: any): Promise<any>; export function updateLastHash(data: any): Promise<any>;
export function saveSeenMessageHashes(data: any): Promise<any>; export function saveSeenMessageHashes(data: any): Promise<any>;
export function saveLegacyMessage(data: any): Promise<any>; export function saveLegacyMessage(data: any): Promise<any>;

@ -4,7 +4,9 @@ import { getAllConversations } from '../../../js/modules/data';
import { ContentMessage, SyncMessage } from '../messages/outgoing'; import { ContentMessage, SyncMessage } from '../messages/outgoing';
import { MultiDeviceProtocol } from '../protocols'; import { MultiDeviceProtocol } from '../protocols';
export function toSyncMessage(message: ContentMessage): SyncMessage | undefined { export function toSyncMessage(
message: ContentMessage
): SyncMessage | undefined {
if (message instanceof SyncMessage) { if (message instanceof SyncMessage) {
return message; return message;
} }
@ -28,22 +30,11 @@ export async function getSyncContacts(): Promise<Array<any> | undefined> {
return []; return [];
} }
console.log('[vince] window.Whisper:', window.Whisper);
console.log('[vince] window.Whisper:', window.Whisper);
console.log('[vince] window.Whisper:', window.Whisper);
console.log('[vince] window.Whisper:', window.Whisper);
const primaryDevice = await MultiDeviceProtocol.getPrimaryDevice(thisDevice); const primaryDevice = await MultiDeviceProtocol.getPrimaryDevice(thisDevice);
const conversations = await getAllConversations({ const conversations = await getAllConversations({
ConversationCollection: window.Whisper.ConversationCollection, ConversationCollection: window.Whisper.ConversationCollection,
}); });
console.log('[vince] conversations:', conversations);
console.log('[vince] conversations:', conversations);
console.log('[vince] conversations:', conversations);
console.log('[vince] conversations:', conversations);
console.log('[vince] conversations:', conversations);
// We are building a set of all contacts // We are building a set of all contacts
const primaryContacts = const primaryContacts =
conversations.filter( conversations.filter(
@ -62,20 +53,20 @@ export async function getSyncContacts(): Promise<Array<any> | undefined> {
c.attributes.secondaryStatus c.attributes.secondaryStatus
); );
const seondaryContactsPromise = secondaryContactsPartial.map(async c => const secondaryContactsPromise = secondaryContactsPartial.map(async c =>
window.ConversationController.getOrCreateAndWait( window.ConversationController.getOrCreateAndWait(
c.getPrimaryDevicePubKey(), c.getPrimaryDevicePubKey(),
'private' 'private'
) )
); );
const secondaryContacts = (await Promise.all(seondaryContactsPromise)) const secondaryContacts = (await Promise.all(secondaryContactsPromise))
// Filter out our primary key if it was added here // Filter out our primary key if it was added here
.filter(c => c.id !== primaryDevice.key); .filter(c => c.id !== primaryDevice.key);
// Return unique contacts // Return unique contacts
return _.uniqBy( return _.uniqBy(
[...primaryContacts, ...secondaryContacts], [...primaryContacts, ...secondaryContacts],
device => !!device 'id'
); );
} }

@ -14,13 +14,10 @@ chai.use(chaiAsPromised);
const { expect } = chai; const { expect } = chai;
describe('Groups Utils', () => { describe('Groups Utils', () => {
describe('getGroupMembers', () => { describe('getGroupMembers', () => {
it('', async () => { it('', async () => {
// //
}); });
}); });
describe('isMediumGroup', () => { describe('isMediumGroup', () => {
@ -28,8 +25,4 @@ describe('Groups Utils', () => {
// //
}); });
}); });
}); });

@ -10,7 +10,6 @@ chai.use(chaiAsPromised);
const { expect } = chai; const { expect } = chai;
describe('Message Utils', () => { describe('Message Utils', () => {
describe('toRawMessage', () => { describe('toRawMessage', () => {
it('can convert to raw message', async () => { it('can convert to raw message', async () => {
const device = TestUtils.generateFakePubKey(); const device = TestUtils.generateFakePubKey();
@ -37,8 +36,14 @@ describe('Message Utils', () => {
const rawBufferJSON = JSON.stringify(rawBuffer); const rawBufferJSON = JSON.stringify(rawBuffer);
const messageBufferJSON = JSON.stringify(message.plainTextBuffer()); const messageBufferJSON = JSON.stringify(message.plainTextBuffer());
expect(rawBuffer instanceof Uint8Array).to.equal(true, 'raw message did not contain a plainTextBuffer'); expect(rawBuffer instanceof Uint8Array).to.equal(
expect(rawBufferJSON).to.equal(messageBufferJSON, 'plainTextBuffer was not converted correctly'); true,
'raw message did not contain a plainTextBuffer'
);
expect(rawBufferJSON).to.equal(
messageBufferJSON,
'plainTextBuffer was not converted correctly'
);
}); });
it('should maintain pubkey', async () => { it('should maintain pubkey', async () => {
@ -49,8 +54,10 @@ describe('Message Utils', () => {
const derivedPubKey = PubKey.from(rawMessage.device); const derivedPubKey = PubKey.from(rawMessage.device);
expect(derivedPubKey).to.exist; expect(derivedPubKey).to.exist;
expect(derivedPubKey?.isEqual(device)).to.equal(true, 'pubkey of message was not converted correctly'); expect(derivedPubKey?.isEqual(device)).to.equal(
true,
'pubkey of message was not converted correctly'
);
}); });
}); });
}); });

@ -14,7 +14,6 @@ chai.use(chaiAsPromised);
const { expect } = chai; const { expect } = chai;
describe('Promise Utils', () => { describe('Promise Utils', () => {
describe('poll', () => { describe('poll', () => {
it('', async () => { it('', async () => {
// //
@ -25,16 +24,11 @@ describe('Promise Utils', () => {
it('', async () => { it('', async () => {
// //
}); });
}); });
describe('waitUntil', () => { describe('waitUntil', () => {
it('', async () => { it('', async () => {
// //
}); });
}); });
}); });

@ -14,13 +14,10 @@ chai.use(chaiAsPromised);
const { expect } = chai; const { expect } = chai;
describe('String Utils', () => { describe('String Utils', () => {
describe('encode', () => { describe('encode', () => {
it('', async () => { it('', async () => {
// //
}); });
}); });
describe('decode', () => { describe('decode', () => {
@ -28,5 +25,4 @@ describe('String Utils', () => {
// //
}); });
}); });
}); });

@ -6,8 +6,8 @@ import { SyncMessageUtils } from '../../../session/utils/';
import { SyncMessage } from '../../../session/messages/outgoing'; import { SyncMessage } from '../../../session/messages/outgoing';
import { TestUtils } from '../../test-utils'; import { TestUtils } from '../../test-utils';
import { UserUtil } from '../../../util'; import { UserUtil } from '../../../util';
import { generateFakePubKey } from '../../test-utils/testUtils';
import { MultiDeviceProtocol } from '../../../session/protocols'; import { MultiDeviceProtocol } from '../../../session/protocols';
import { Integer } from '../../../types/Util';
// tslint:disable-next-line: no-require-imports no-var-requires // tslint:disable-next-line: no-require-imports no-var-requires
const chaiAsPromised = require('chai-as-promised'); const chaiAsPromised = require('chai-as-promised');
@ -16,7 +16,6 @@ chai.use(chaiAsPromised);
const { expect } = chai; const { expect } = chai;
describe('Sync Message Utils', () => { describe('Sync Message Utils', () => {
describe('toSyncMessage', () => { describe('toSyncMessage', () => {
it('can convert to sync message', async () => { it('can convert to sync message', async () => {
const message = TestUtils.generateChatMessage(); const message = TestUtils.generateChatMessage();
@ -28,8 +27,6 @@ describe('Sync Message Utils', () => {
// Further tests required // Further tests required
}); });
}); });
describe('canSync', () => { describe('canSync', () => {
@ -48,64 +45,119 @@ describe('Sync Message Utils', () => {
const canSync = SyncMessageUtils.canSync(message); const canSync = SyncMessageUtils.canSync(message);
expect(canSync).to.equal(false, ''); expect(canSync).to.equal(false, '');
}); });
}); });
// describe('getSyncContacts', () => { describe('getSyncContacts', () => {
// let getAllConversationsStub: sinon.SinonStub; let getAllConversationsStub: sinon.SinonStub;
let getOrCreateAndWaitStub: sinon.SinonStub;
let getOrCreatAndWaitItem: any;
// tslint:disable-next-line: insecure-random
const randomBoolean = () => !!Math.round(Math.random());
const randomMockConv = (primary: boolean) => (
// new (function(primary) {
// const primaryDevicePubkey = generateFakePubKey().key; // return {
// let conversations = [ // id: generateFakePubKey().key,
// {
// isPrivate: () => true, // isPrivate: () => true,
// isOurLocalDevice: () => false, // isOurLocalDevice: () => false,
// isBlocked: () => false, // isBlocked: () => false,
// getPrimaryDevicePubKey: () => primaryDevicePubkey, // getPrimaryDevicePubKey: () => this.isPrivate ?
// attributes: { // attributes: {
// secondaryStatus: undefined, // secondaryStatus: !primary,
// }, // },
// }, // };
// ]; // })();
{}
);
// Fill half with secondaries, half with primaries
const numConversations = 20;
const primaryConversations = new Array(numConversations / 2)
.fill({})
.map(() => randomMockConv(true));
const secondaryConversations = new Array(numConversations / 2)
.fill({})
.map(() => randomMockConv(false));
const conversations = [...primaryConversations, ...secondaryConversations];
const sandbox = sinon.createSandbox();
const ourDevice = TestUtils.generateFakePubKey();
const ourNumber = ourDevice.key;
const ourPrimaryDevice = TestUtils.generateFakePubKey();
// const sandbox = sinon.createSandbox(); beforeEach(async () => {
// const ourDevice = TestUtils.generateFakePubKey(); // Util Stubs
// const ourNumber = ourDevice.key; TestUtils.stubWindow('Whisper', {
ConversationCollection: sandbox.stub(),
});
// const ourPrimaryDevice = TestUtils.generateFakePubKey(); getAllConversationsStub = TestUtils.stubData(
// const ourPrimaryNumber = ourPrimaryDevice.key; 'getAllConversations'
).resolves(conversations);
// beforeEach(async () => { // Scale result in sync with secondaryConversations on callCount
getOrCreateAndWaitStub = sandbox.stub().callsFake(() => {
const item = secondaryConversations[getOrCreateAndWaitStub.callCount - 1];
// getAllConversationsStub = TestUtils.stubData('getAllConversations').resolves(conversations); // Make the item a primary device to match the call in SyncMessage under secondaryContactsPromise
getOrCreatAndWaitItem = {
...item,
getPrimaryDevicePubKey: () => item.id,
attributes: {
secondaryStatus: false,
},
};
// // Stubs return getOrCreatAndWaitItem;
// sandbox.stub(UserUtil, 'getCurrentDevicePubKey').resolves(ourNumber); });
// sandbox.stub(MultiDeviceProtocol, 'getPrimaryDevice').resolves(ourPrimaryDevice);
// }); TestUtils.stubWindow('ConversationController', {
getOrCreateAndWait: getOrCreateAndWaitStub,
});
// afterEach(() => { // Stubs
// sandbox.restore(); sandbox.stub(UserUtil, 'getCurrentDevicePubKey').resolves(ourNumber);
// }); sandbox
.stub(MultiDeviceProtocol, 'getPrimaryDevice')
.resolves(ourPrimaryDevice);
});
// it('can get sync contacts', async () => { afterEach(() => {
// // MAKE MORE SPECIFIC, CHECK PARAMETERS sandbox.restore();
TestUtils.restoreStubs();
});
// const contacts = await SyncMessageUtils.getSyncContacts(); it('can get sync contacts with only primary contacts', async () => {
getAllConversationsStub.resolves(primaryConversations);
// console.log('[vince] contacts:', contacts); const contacts = await SyncMessageUtils.getSyncContacts();
// console.log('[vince] contacts:', contacts); expect(getAllConversationsStub.callCount).to.equal(1);
// console.log('[vince] getAllConversationsStub.callCount:', getAllConversationsStub.callCount);
// console.log('[vince] getAllConversationsStub.callCount:', getAllConversationsStub.callCount);
// }); // Each contact should be a primary device
expect(contacts).to.have.length(numConversations / 2);
expect(contacts?.find(c => c.attributes.secondaryStatus)).to.not.exist;
});
it('can get sync contacts of assorted primaries and secondaries', async () => {
// Map secondary contacts to stub resolution
const contacts = await SyncMessageUtils.getSyncContacts();
expect(getAllConversationsStub.callCount).to.equal(1);
// }); // We should have numConversations unique contacts
expect(contacts).to.have.length(numConversations);
// All contacts should be primary; half of which some from secondaries in secondaryContactsPromise
expect(contacts?.find(c => c.attributes.secondaryStatus)).to.not.exist;
expect(contacts)
});
});
// MAKE MORE SPECIFIC, CHECK PARAMETERS
}); });

@ -4,13 +4,14 @@ import * as window from '../../window';
import * as DataShape from '../../../js/modules/data'; import * as DataShape from '../../../js/modules/data';
import { v4 as uuid } from 'uuid'; import { v4 as uuid } from 'uuid';
import { PubKey } from '../../../ts/session/types'; import { OpenGroup, PubKey } from '../../../ts/session/types';
import { import {
ChatMessage, ChatMessage,
ClosedGroupChatMessage, ClosedGroupChatMessage,
OpenGroupMessage, OpenGroupMessage,
} from '../../session/messages/outgoing'; } from '../../session/messages/outgoing';
import { OpenGroup } from '../../session/types/OpenGroup'; import { Integer } from '../../types/Util';
import { ConversationModel, ConversationAttributes } from '../../../js/models/conversation';
const globalAny: any = global; const globalAny: any = global;
const sandbox = sinon.createSandbox(); const sandbox = sinon.createSandbox();
@ -78,11 +79,11 @@ export function generateFakePubKey(): PubKey {
return new PubKey(pubkeyString); return new PubKey(pubkeyString);
} }
export function generateFakePubKeys(amount: number): Array<PubKey> { export function generateFakePubKeys(amount: Integer): Array<PubKey> {
const numPubKeys = amount > 0 ? Math.floor(amount) : 0; const numPubKeys = amount > 0 ? Math.floor(amount) : 0;
// tslint:disable-next-line: no-unnecessary-callback-wrapper // tslint:disable-next-line: no-unnecessary-callback-wrapper
return new Array(numPubKeys).fill(0).map(() => generateFakePubKey()); return new Array(amount).fill(0).map(() => generateFakePubKey());
} }
export function generateChatMessage(identifier?: string): ChatMessage { export function generateChatMessage(identifier?: string): ChatMessage {
@ -124,3 +125,39 @@ export function generateClosedGroupMessage(
chatMessage: generateChatMessage(), chatMessage: generateChatMessage(),
}); });
} }
// Mock ConversationModel
export class MockPrivateConversation implements ConversationModel {
public id: string;
public isPrimary: boolean;
public attributes: ConversationAttributes;
constructor(isPrimary: boolean) {
this.isPrimary = isPrimary;
this.id = TestUtils.generateFakePubKey().key;
this.attributes = {
members
}
}
public isPrivate() {
return true;
}
public isOurLocalDevice() {
return false;
}
public isBlocked() {
return false;
}
public getPrimaryDevicePubKey() {
return this.isPrimary
? this.id
: TestUtils.generateFakePubKey().key;
}
}
const myconv = new MockPrivateConversation(false) ;

@ -1,3 +1,8 @@
// Integer Type - primarily for incremental values in ConversationModel etc
export type Integer = number & { __int__: void };
export const roundToInt = (num: number): Integer => Math.round(num) as Integer;
export type RenderTextCallbackType = (options: { export type RenderTextCallbackType = (options: {
text: string; text: string;
key: number; key: number;

Loading…
Cancel
Save