Skip to content

Commit

Permalink
feat: update to 1.0 spec. Fix test setup
Browse files Browse the repository at this point in the history
Signed-off-by: Ariel Gentile <gentilester@gmail.com>
  • Loading branch information
genaris committed Jun 21, 2023
1 parent 213c840 commit 7f4e8e7
Show file tree
Hide file tree
Showing 12 changed files with 1,313 additions and 959 deletions.
12 changes: 6 additions & 6 deletions jest.config.base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ const config: Config.InitialOptions = {
preset: 'ts-jest',
testEnvironment: 'node',
coveragePathIgnorePatterns: ['/build/', '/node_modules/', '/__tests__/', 'test'],
coverageDirectory: '<rootDir>/coverage/',
verbose: true,
testMatch: ['**/?(*.)+(spec|test).[tj]s?(x)'],
moduleNameMapper: {
'@2060-agent-sdk/(.+)': [
'<rootDir>/../../packages/$1/src',
'<rootDir>/../packages/$1/src',
'<rootDir>/packages/$1/src',
transform: {
'^.+\\.tsx?$': [
'ts-jest',
{
isolatedModules: true,
},
],
},
}
Expand Down
1 change: 0 additions & 1 deletion jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import packageJson from './package.json'

const config: Config.InitialOptions = {
...base,
name: packageJson.name,
displayName: packageJson.name,
setupFilesAfterEnv: ['./test/setup.ts'],
testTimeout: 15000,
Expand Down
28 changes: 18 additions & 10 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
"check-types": "tsc --noEmit -p tsconfig.build.json",
"check-format": "yarn prettier --check",
"prettier": "prettier --ignore-path .gitignore '**/*.+(js|json|ts|md|yml|yaml)'",
"release": "release-it"
"release": "release-it",
"test": "jest"
},
"repository": {
"type": "git",
Expand All @@ -32,28 +33,35 @@
"registry": "https://registry.npmjs.org/"
},
"devDependencies": {
"@aries-framework/node": "^0.4.0-alpha.110",
"@aries-framework/askar": "^0.4.0",
"@aries-framework/node": "^0.4.0",
"@hyperledger/aries-askar-nodejs": "^0.1.0",
"@types/jest": "^26.0.23",
"@types/node": "^16.11.7",
"@types/node-fetch": "^2.6.4",
"@types/uuid": "^9.0.0",
"@typescript-eslint/eslint-plugin": "^4.28.2",
"@typescript-eslint/parser": "^4.17.0",
"release-it": "^14.13.1",
"jest": "^27.0.4",
"@typescript-eslint/eslint-plugin": "^5.48.1",
"@typescript-eslint/parser": "^5.48.1",
"jest": "^29.5.0",
"prettier": "^2.2.1",
"ts-jest": "^27.0.3",
"release-it": "^14.13.1",
"ts-jest": "^29.0.5",
"ts-node": "^10.8.1",
"tsconfig-paths": "^3.10.1",
"typescript": "~4.3.0"
"tsconfig-paths": "^4.1.2",
"typescript": "~4.9.4"
},
"dependencies": {
"@aries-framework/core": "^0.4.0-alpha.110",
"@aries-framework/core": "^0.4.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.2.0",
"tsyringe": "^4.7.0",
"uuid": "^9.0.0"
},
"resolutions": {
"ref-napi": "npm:@2060.io/ref-napi"
},
"release-it": {
"github": {
"release": true
Expand Down
14 changes: 11 additions & 3 deletions src/MediaSharingApi.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import {
AgentContext,
ConnectionService,
Dispatcher,
injectable,
MessageHandlerRegistry,
MessageSender,
OutboundMessageContext,
} from '@aries-framework/core'
Expand Down Expand Up @@ -108,10 +106,20 @@ export class MediaSharingApi {
/**
* Find a record by id
*
* @param recordId the record id
* @param recordId the record id
* @returns the record or null if not found
*/
public findById(recordId: string): Promise<MediaSharingRecord | null> {
return this.mediaSharingService.findById(this.agentContext, recordId)
}

/**
* Find a record by thread id
*
* @param recordId the record id
* @returns the record or null if not found
*/
public findByThreadId(recordId: string): Promise<MediaSharingRecord | null> {
return this.mediaSharingService.findByThreadId(this.agentContext, recordId)
}
}
61 changes: 55 additions & 6 deletions src/messages/ShareMediaMessage.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,37 @@
import { AgentMessage, IsValidMessageType, parseMessageType } from '@aries-framework/core'
import { AgentMessage, Attachment, IsValidMessageType, parseMessageType } from '@aries-framework/core'
import { DateParser } from '@aries-framework/core/build/utils/transformers'
import { Expose, Transform, Type } from 'class-transformer'
import { IsDate, IsOptional, IsString } from 'class-validator'
import { SharedMediaItem } from '../repository'
import { CipheringInfo, SharedMediaItem } from '../repository'

interface SharedMediaItemDescriptorOptions {
id: string
attachmentId: string
description?: string
ciphering?: CipheringInfo
metadata?: Record<string, unknown>
}

class SharedMediaItemDescriptor {
@Expose({ name: '@id' })
public id!: string

@Expose({ name: 'attachment_id' })
public attachmentId!: string

public ciphering?: CipheringInfo

public metadata?: Record<string, unknown>

public constructor(options: SharedMediaItemDescriptorOptions) {
if (options) {
this.id = options.id
this.attachmentId = options.attachmentId
this.ciphering = options.ciphering
this.metadata = options.metadata
}
}
}

export interface ShareMediaMessageOptions {
id?: string
Expand Down Expand Up @@ -33,7 +62,27 @@ export class ShareMediaMessage extends AgentMessage {

this.sentTime = options.sentTime || new Date()
this.description = options.description
this.items = options.items

// Assign an attachment per item using index as id
this.items = []

for (var i = 0; i < options.items.length; i++) {
const item = options.items[i]
this.addAppendedAttachment(new Attachment({
id: i.toString(),
data: { links: [item.uri] },
byteCount: item.byteCount,
filename: item.fileName,
description: item.description,
mimeType: item.mimeType,
}))
this.items.push({
id: item.id,
attachmentId: i.toString(),
ciphering: item.ciphering,
metadata: item.metadata,
})
}
}
}

Expand All @@ -46,10 +95,10 @@ export class ShareMediaMessage extends AgentMessage {
@IsDate()
public sentTime!: Date

@Type(() => SharedMediaItem)
public items!: SharedMediaItem[]
@Type(() => SharedMediaItemDescriptor)
public items!: SharedMediaItemDescriptor[]

@IsValidMessageType(ShareMediaMessage.type)
public readonly type = ShareMediaMessage.type.messageTypeUri
public static readonly type = parseMessageType('https://2060.io/didcomm/media-sharing/0.1/share-media')
public static readonly type = parseMessageType('https://didcomm.org/media-sharing/1.0/share-media')
}
31 changes: 21 additions & 10 deletions src/repository/MediaSharingRecord.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,43 @@
import { v4 as uuid } from 'uuid'
import { AriesFrameworkError, Attachment, AttachmentData, BaseRecord } from '@aries-framework/core'
import { AriesFrameworkError, BaseRecord, utils } from '@aries-framework/core'
import { MediaSharingRole, MediaSharingState } from '../model'
import { AttachmentOptions } from '@aries-framework/core/build/decorators/attachment/Attachment'
import { Exclude, Type } from 'class-transformer'
import { Type } from 'class-transformer'

export interface CipheringInfo {
algorithm: string
parameters: Record<string, unknown>
}

export interface SharedMediaItemOptions extends Omit<AttachmentOptions, 'data'> {
export interface SharedMediaItemOptions {
id?: string
uri: string
mimeType: string
description?: string
byteCount?: number
fileName?: string
ciphering?: CipheringInfo
metadata?: Record<string, unknown>
}

export class SharedMediaItem extends Attachment {
@Exclude()
public get uri() {
return this.data.links ? this.data.links[0] : undefined
}
export class SharedMediaItem {

public id!: string
public uri!: string
public mimeType!: string
public description?: string
public byteCount?: number
public fileName?: string
public ciphering?: CipheringInfo
public metadata?: Record<string, unknown>

public constructor(options: SharedMediaItemOptions) {
super({ ...options, data: new AttachmentData({ links: [options?.uri] }) })
if (options) {
this.id = options.id ?? utils.uuid()
this.uri = options.uri
this.mimeType = options.mimeType
this.description = options.description
this.byteCount = options.byteCount
this.fileName = options.fileName
this.ciphering = options.ciphering
this.metadata = options.metadata
}
Expand Down
36 changes: 33 additions & 3 deletions src/services/MediaSharingService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { AgentContext, AriesFrameworkError, EventEmitter, MessageHandlerInboundM
import { Lifecycle, scoped } from 'tsyringe'

import { MediaSharingEventTypes, MediaSharingStateChangedEvent } from '../MediaSharingEvents'
import { MediaSharingRepository, MediaSharingRecord } from '../repository'
import { MediaSharingRepository, MediaSharingRecord, SharedMediaItem } from '../repository'
import { ShareMediaMessage } from '../messages'
import { ShareMediaHandler } from '../handlers'
import { MediaSharingRole, MediaSharingState } from '../model'
Expand Down Expand Up @@ -113,14 +113,44 @@ export class MediaSharingService {
throw new AriesFrameworkError('There are no valid items in MediaSharingRecord')
}

// Process items
const items: SharedMediaItem[] = []

for (const item of message.items) {
const relatedAttachment = message.appendedAttachments?.find(attachment => attachment .id === item.attachmentId)
if (!relatedAttachment) {
throw new AriesFrameworkError(`No attachment found for shared item ${item.id}`)
}

if (!relatedAttachment.mimeType) {
throw new AriesFrameworkError(`Missing MIME type for shared item ${item.id}`)
}

if (!relatedAttachment.data.links || !relatedAttachment.data.links.length) {
throw new AriesFrameworkError(`Missing URI for for shared item ${item.id}`)
}

items.push({
id: item.id,
ciphering: item.ciphering,
metadata: item.metadata,
mimeType: relatedAttachment.mimeType,
uri: relatedAttachment.data.links[0],
byteCount: relatedAttachment.byteCount,
description: relatedAttachment.description,
fileName: relatedAttachment.filename,

})
}

// New record
const record = new MediaSharingRecord({
connectionId: connection.id,
threadId: message.id,
parentThreadId: messageContext.message.thread?.parentThreadId,
state: MediaSharingState.MediaShared,
role: MediaSharingRole.Receiver,
items: message.items,
items,
description: message.description,
sentTime: message.sentTime,
})
Expand All @@ -140,7 +170,7 @@ export class MediaSharingService {
}

/**
* Retrieve all auth code records
* Retrieve all media sharing records
*
* @returns List containing all auth code records
*/
Expand Down
12 changes: 6 additions & 6 deletions test/mediasharing.test.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
import { agentDependencies } from '@aries-framework/node'
import { AskarModule } from '@aries-framework/askar'
import { ariesAskar } from '@hyperledger/aries-askar-nodejs'
import {
Agent,
ConnectionRecord,
ConsoleLogger,
EncryptedMessage,
JsonTransformer,
LogLevel,
} from '@aries-framework/core'
import { v4 as uuid } from 'uuid'
import { firstValueFrom, ReplaySubject, Subject } from 'rxjs'
import { MediaSharingModule } from '../src/MediaSharingModule'
import { MediaSharingRecord, SharedMediaItem } from '../src/repository'
import { MediaSharingRecord } from '../src/repository'
import { SubjectOutboundTransport } from './transport/SubjectOutboundTransport'
import { SubjectInboundTransport } from './transport/SubjectInboundTransport'
import { recordsAddedByType } from './recordUtils'

const logger = new ConsoleLogger(LogLevel.info)
const logger = new ConsoleLogger(LogLevel.debug)

export type SubjectMessage = {
message: EncryptedMessage
Expand Down Expand Up @@ -55,7 +56,7 @@ describe('media test', () => {
logger,
},
dependencies: agentDependencies,
modules: { media: new MediaSharingModule() },
modules: { askar: new AskarModule({ ariesAskar }), media: new MediaSharingModule() },
})

aliceAgent.registerOutboundTransport(new SubjectOutboundTransport(subjectMap))
Expand All @@ -71,7 +72,7 @@ describe('media test', () => {
logger,
},
dependencies: agentDependencies,
modules: { media: new MediaSharingModule() },
modules: { askar: new AskarModule({ ariesAskar }), media: new MediaSharingModule() },
})

bobAgent.registerOutboundTransport(new SubjectOutboundTransport(subjectMap))
Expand Down Expand Up @@ -146,7 +147,6 @@ describe('media test', () => {
const bobRecord = await firstValueFrom(subjectBob)
await firstValueFrom(subjectAlice)

console.log(bobRecord.items![0])
expect(bobRecord.items?.length).toBe(1)
expect(bobRecord.items![0].mimeType).toBe('image/png')
expect(bobRecord.items![0].uri).toBe('http://blabla')
Expand Down
Loading

0 comments on commit 7f4e8e7

Please sign in to comment.