mirror of
https://github.com/element-hq/element-call.git
synced 2026-10-22 21:53:14 +00:00
Update matrix
This commit is contained in:
1 parent
09d726a5a8
commit
cc7eb26d7c
2 files changed
+1790
-1570
No files matched your search
+1762
-1544
File diff suppressed because it is too large.
Load diff
@@ -118,7 +118,7 @@
|
||||
"src/filter.ts",
|
||||
"src/http-api.js",
|
||||
"src/indexeddb-helpers.ts",
|
||||
"src/interactive-auth.js",
|
||||
"src/interactive-auth.ts",
|
||||
"src/logger.ts",
|
||||
"src/matrix.ts",
|
||||
"src/models/MSC3089Branch.ts",
|
||||
@@ -134,11 +134,12 @@
|
||||
"src/models/room-summary.ts",
|
||||
"src/models/room.ts",
|
||||
"src/models/search-result.ts",
|
||||
"src/models/thread.ts",
|
||||
"src/models/user.ts",
|
||||
"src/pushprocessor.js",
|
||||
"src/pushprocessor.ts",
|
||||
"src/randomstring.ts",
|
||||
"src/realtime-callbacks.js",
|
||||
"src/scheduler.js",
|
||||
"src/scheduler.ts",
|
||||
"src/service-types.ts",
|
||||
"src/store/indexeddb-local-backend.ts",
|
||||
"src/store/indexeddb-remote-backend.ts",
|
||||
@@ -157,7 +158,7 @@
|
||||
"src/webrtc/callFeed.ts"
|
||||
],
|
||||
"names": [],
|
||||
"mappings": "AAAA;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACXA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACPA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACdA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/BA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5CA;AACA;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACALine truncated
|
||||
"mappings": "AAAA;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACXA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACPA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACdA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/BA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5CA;AACA;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACALine truncated
|
||||
"file": "generated.js",
|
||||
"sourceRoot": "",
|
||||
"sourcesContent": [
|
||||
@@ -180,7 +181,7 @@
|
||||
"function _iterableToArrayLimit(arr, i) {\n var _i = arr == null ? null : typeof Symbol !== \"undefined\" && arr[Symbol.iterator] || arr[\"@@iterator\"];\n\n if (_i == null) return;\n var _arr = [];\n var _n = true;\n var _d = false;\n\n var _s, _e;\n\n try {\n for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}\n\nmodule.exports = _iterableToArrayLimit;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;",
|
||||
"function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nmodule.exports = _nonIterableRest;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;",
|
||||
"function _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nmodule.exports = _nonIterableSpread;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;",
|
||||
"var _typeof = require(\"@babel/runtime/helpers/typeof\")[\"default\"];\n\nvar assertThisInitialized = require(\"./assertThisInitialized.js\");\n\nfunction _possibleConstructorReturn(self, call) {\n if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) {\n return call;\n }\n\n return assertThisInitialized(self);\n}\n\nmodule.exports = _possibleConstructorReturn;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;",
|
||||
"var _typeof = require(\"@babel/runtime/helpers/typeof\")[\"default\"];\n\nvar assertThisInitialized = require(\"./assertThisInitialized.js\");\n\nfunction _possibleConstructorReturn(self, call) {\n if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) {\n return call;\n } else if (call !== void 0) {\n throw new TypeError(\"Derived constructors may only return object or undefined\");\n }\n\n return assertThisInitialized(self);\n}\n\nmodule.exports = _possibleConstructorReturn;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;",
|
||||
"function _setPrototypeOf(o, p) {\n module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n module.exports[\"default\"] = module.exports, module.exports.__esModule = true;\n return _setPrototypeOf(o, p);\n}\n\nmodule.exports = _setPrototypeOf;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;",
|
||||
"var arrayWithHoles = require(\"./arrayWithHoles.js\");\n\nvar iterableToArrayLimit = require(\"./iterableToArrayLimit.js\");\n\nvar unsupportedIterableToArray = require(\"./unsupportedIterableToArray.js\");\n\nvar nonIterableRest = require(\"./nonIterableRest.js\");\n\nfunction _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();\n}\n\nmodule.exports = _slicedToArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;",
|
||||
"var arrayWithoutHoles = require(\"./arrayWithoutHoles.js\");\n\nvar iterableToArray = require(\"./iterableToArray.js\");\n\nvar unsupportedIterableToArray = require(\"./unsupportedIterableToArray.js\");\n\nvar nonIterableSpread = require(\"./nonIterableSpread.js\");\n\nfunction _toConsumableArray(arr) {\n return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();\n}\n\nmodule.exports = _toConsumableArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;",
|
||||
@@ -219,7 +220,7 @@
|
||||
"// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n// If obj.hasOwnProperty has been overridden, then calling\n// obj.hasOwnProperty(prop) will break.\n// See: https://github.com/joyent/node/issues/1707\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nmodule.exports = function(qs, sep, eq, options) {\n sep = sep || '&';\n eq = eq || '=';\n var obj = {};\n\n if (typeof qs !== 'string' || qs.length === 0) {\n return obj;\n }\n\n var regexp = /\\+/g;\n qs = qs.split(sep);\n\n var maxKeys = 1000;\n if (options && typeof options.maxKeys === 'number') {\n maxKeys = options.maxKeys;\n }\n\n var len = qs.length;\n // maxKeys <= 0 means that we should not limit keys count\n if (maxKeys > 0 && len > maxKeys) {\n len = maxKeys;\n }\n\n for (var i = 0; i < len; ++i) {\n var x = qs[i].replace(regexp, '%20'),\n idx = x.indexOf(eq),\n kstr, vstr, k, v;\n\n if (idx >= 0) {\n kstr = x.substr(0, idx);\n vstr = x.substr(idx + 1);\n } else {\n kstr = x;\n vstr = '';\n }\n\n k = decodeURIComponent(kstr);\n v = decodeURIComponent(vstr);\n\n if (!hasOwnProperty(obj, k)) {\n obj[k] = v;\n } else if (isArray(obj[k])) {\n obj[k].push(v);\n } else {\n obj[k] = [obj[k], v];\n }\n }\n\n return obj;\n};\n\nvar isArray = Array.isArray || function (xs) {\n return Object.prototype.toString.call(xs) === '[object Array]';\n};\n",
|
||||
"// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar stringifyPrimitive = function(v) {\n switch (typeof v) {\n case 'string':\n return v;\n\n case 'boolean':\n return v ? 'true' : 'false';\n\n case 'number':\n return isFinite(v) ? v : '';\n\n default:\n return '';\n }\n};\n\nmodule.exports = function(obj, sep, eq, name) {\n sep = sep || '&';\n eq = eq || '=';\n if (obj === null) {\n obj = undefined;\n }\n\n if (typeof obj === 'object') {\n return map(objectKeys(obj), function(k) {\n var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;\n if (isArray(obj[k])) {\n return map(obj[k], function(v) {\n return ks + encodeURIComponent(stringifyPrimitive(v));\n }).join(sep);\n } else {\n return ks + encodeURIComponent(stringifyPrimitive(obj[k]));\n }\n }).join(sep);\n\n }\n\n if (!name) return '';\n return encodeURIComponent(stringifyPrimitive(name)) + eq +\n encodeURIComponent(stringifyPrimitive(obj));\n};\n\nvar isArray = Array.isArray || function (xs) {\n return Object.prototype.toString.call(xs) === '[object Array]';\n};\n\nfunction map (xs, f) {\n if (xs.map) return xs.map(f);\n var res = [];\n for (var i = 0; i < xs.length; i++) {\n res.push(f(xs[i], i));\n }\n return res;\n}\n\nvar objectKeys = Object.keys || function (obj) {\n var res = [];\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);\n }\n return res;\n};\n",
|
||||
"'use strict';\n\nexports.decode = exports.parse = require('./decode');\nexports.encode = exports.stringify = require('./encode');\n",
|
||||
"/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar runtime = (function (exports) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n function define(obj, key, value) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n return obj[key];\n }\n try {\n // IE 8 has a broken Object.defineProperty that only works on DOM objects.\n define({}, \"\");\n } catch (err) {\n define = function(obj, key, value) {\n return obj[key] = value;\n };\n }\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n exports.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n IteratorPrototype[iteratorSymbol] = function () {\n return this;\n };\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n GeneratorFunctionPrototype.constructor = GeneratorFunction;\n GeneratorFunction.displayName = define(\n GeneratorFunctionPrototype,\n toStringTagSymbol,\n \"GeneratorFunction\"\n );\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n define(prototype, method, function(arg) {\n return this._invoke(method, arg);\n });\n });\n }\n\n exports.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name proLine truncated
|
||||
"/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar runtime = (function (exports) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n function define(obj, key, value) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n return obj[key];\n }\n try {\n // IE 8 has a broken Object.defineProperty that only works on DOM objects.\n define({}, \"\");\n } catch (err) {\n define = function(obj, key, value) {\n return obj[key] = value;\n };\n }\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n exports.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n define(IteratorPrototype, iteratorSymbol, function () {\n return this;\n });\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = GeneratorFunctionPrototype;\n define(Gp, \"constructor\", GeneratorFunctionPrototype);\n define(GeneratorFunctionPrototype, \"constructor\", GeneratorFunction);\n GeneratorFunction.displayName = define(\n GeneratorFunctionPrototype,\n toStringTagSymbol,\n \"GeneratorFunction\"\n );\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n define(prototype, method, function(arg) {\n return this._invoke(method, arg);\n });\n });\n }\n\n exports.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction construLine truncated
|
||||
"module.exports = require('./lib/retry');",
|
||||
"var RetryOperation = require('./retry_operation');\n\nexports.operation = function(options) {\n var timeouts = exports.timeouts(options);\n return new RetryOperation(timeouts, {\n forever: options && (options.forever || options.retries === Infinity),\n unref: options && options.unref,\n maxRetryTime: options && options.maxRetryTime\n });\n};\n\nexports.timeouts = function(options) {\n if (options instanceof Array) {\n return [].concat(options);\n }\n\n var opts = {\n retries: 10,\n factor: 2,\n minTimeout: 1 * 1000,\n maxTimeout: Infinity,\n randomize: false\n };\n for (var key in options) {\n opts[key] = options[key];\n }\n\n if (opts.minTimeout > opts.maxTimeout) {\n throw new Error('minTimeout is greater than maxTimeout');\n }\n\n var timeouts = [];\n for (var i = 0; i < opts.retries; i++) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n if (options && options.forever && !timeouts.length) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n // sort the array numerically ascending\n timeouts.sort(function(a,b) {\n return a - b;\n });\n\n return timeouts;\n};\n\nexports.createTimeout = function(attempt, opts) {\n var random = (opts.randomize)\n ? (Math.random() + 1)\n : 1;\n\n var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));\n timeout = Math.min(timeout, opts.maxTimeout);\n\n return timeout;\n};\n\nexports.wrap = function(obj, options, methods) {\n if (options instanceof Array) {\n methods = options;\n options = null;\n }\n\n if (!methods) {\n methods = [];\n for (var key in obj) {\n if (typeof obj[key] === 'function') {\n methods.push(key);\n }\n }\n }\n\n for (var i = 0; i < methods.length; i++) {\n var method = methods[i];\n var original = obj[method];\n\n obj[method] = function retryWrapper(original) {\n var op = exports.operation(options);\n var args = Array.prototype.slice.call(arguments, 1);\n var callback = args.pop();\n\n args.push(function(err) {\n if (op.retry(err)) {\n return;\n }\n if (err) {\n arguments[0] = op.mainError();\n }\n callback.apply(this, arguments);\n });\n\n op.attempt(function() {\n original.apply(obj, args);\n });\n }.bind(obj, original);\n obj[method].options = options;\n }\n};\n",
|
||||
"function RetryOperation(timeouts, options) {\n // Compatibility for the old (timeouts, retryForever) signature\n if (typeof options === 'boolean') {\n options = { forever: options };\n }\n\n this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));\n this._timeouts = timeouts;\n this._options = options || {};\n this._maxRetryTime = options && options.maxRetryTime || Infinity;\n this._fn = null;\n this._errors = [];\n this._attempts = 1;\n this._operationTimeout = null;\n this._operationTimeoutCb = null;\n this._timeout = null;\n this._operationStart = null;\n this._timer = null;\n\n if (this._options.forever) {\n this._cachedTimeouts = this._timeouts.slice(0);\n }\n}\nmodule.exports = RetryOperation;\n\nRetryOperation.prototype.reset = function() {\n this._attempts = 1;\n this._timeouts = this._originalTimeouts.slice(0);\n}\n\nRetryOperation.prototype.stop = function() {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n if (this._timer) {\n clearTimeout(this._timer);\n }\n\n this._timeouts = [];\n this._cachedTimeouts = null;\n};\n\nRetryOperation.prototype.retry = function(err) {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n\n if (!err) {\n return false;\n }\n var currentTime = new Date().getTime();\n if (err && currentTime - this._operationStart >= this._maxRetryTime) {\n this._errors.push(err);\n this._errors.unshift(new Error('RetryOperation timeout occurred'));\n return false;\n }\n\n this._errors.push(err);\n\n var timeout = this._timeouts.shift();\n if (timeout === undefined) {\n if (this._cachedTimeouts) {\n // retry forever, only keep last error\n this._errors.splice(0, this._errors.length - 1);\n timeout = this._cachedTimeouts.slice(-1);\n } else {\n return false;\n }\n }\n\n var self = this;\n this._timer = setTimeout(function() {\n self._attempts++;\n\n if (self._operationTimeoutCb) {\n self._timeout = setTimeout(function() {\n self._operationTimeoutCb(self._attempts);\n }, self._operationTimeout);\n\n if (self._options.unref) {\n self._timeout.unref();\n }\n }\n\n self._fn(self._attempts);\n }, timeout);\n\n if (this._options.unref) {\n this._timer.unref();\n }\n\n return true;\n};\n\nRetryOperation.prototype.attempt = function(fn, timeoutOps) {\n this._fn = fn;\n\n if (timeoutOps) {\n if (timeoutOps.timeout) {\n this._operationTimeout = timeoutOps.timeout;\n }\n if (timeoutOps.cb) {\n this._operationTimeoutCb = timeoutOps.cb;\n }\n }\n\n var self = this;\n if (this._operationTimeoutCb) {\n this._timeout = setTimeout(function() {\n self._operationTimeoutCb();\n }, self._operationTimeout);\n }\n\n this._operationStart = new Date().getTime();\n\n this._fn(this._attempts);\n};\n\nRetryOperation.prototype.try = function(fn) {\n console.log('Using RetryOperation.try() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = function(fn) {\n console.log('Using RetryOperation.start() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = RetryOperation.prototype.try;\n\nRetryOperation.prototype.errors = function() {\n return this._errors;\n};\n\nRetryOperation.prototype.attempts = function() {\n return this._attempts;\n};\n\nRetryOperation.prototype.mainError = function() {\n if (this._errors.length === 0) {\n return null;\n }\n\n var counts = {};\n var mainError = null;\n var mainErrorCount = 0;\n\n for (var i = 0; i < this._errors.length; i++) {\n var error = this._errors[i];\n var message = error.message;\n var count = (counts[message] || 0) + 1;\n\n counts[message] = count;\n\n if (count >= mainErrorCount) {\n mainError = error;\n mainErrorCount = count;\n }\n }\n\n return mainError;\n};\n",
|
||||
@@ -229,7 +230,7 @@
|
||||
"'use strict';\n\n\nvar data = require('./data.json');\n\nfunction escapeRegexp(str) {\n return str.replace(/([.?*+^$[\\]\\\\(){}|-])/g, '\\\\$1');\n}\n\nvar REPLACE_RE = RegExp(Object.keys(data).map(escapeRegexp).join('|'), 'g');\n\nfunction replace_fn(match) {\n return data[match];\n}\n\nfunction unhomoglyph(str) {\n return str.replace(REPLACE_RE, replace_fn);\n}\n\nmodule.exports = unhomoglyph;\n",
|
||||
"// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar punycode = require('punycode');\nvar util = require('./util');\n\nexports.parse = urlParse;\nexports.resolve = urlResolve;\nexports.resolveObject = urlResolveObject;\nexports.format = urlFormat;\n\nexports.Url = Url;\n\nfunction Url() {\n this.protocol = null;\n this.slashes = null;\n this.auth = null;\n this.host = null;\n this.port = null;\n this.hostname = null;\n this.hash = null;\n this.search = null;\n this.query = null;\n this.pathname = null;\n this.path = null;\n this.href = null;\n}\n\n// Reference: RFC 3986, RFC 1808, RFC 2396\n\n// define these here so at least they only have to be\n// compiled once on the first module load.\nvar protocolPattern = /^([a-z0-9.+-]+:)/i,\n portPattern = /:[0-9]*$/,\n\n // Special case for a simple path URL\n simplePathPattern = /^(\\/\\/?(?!\\/)[^\\?\\s]*)(\\?[^\\s]*)?$/,\n\n // RFC 2396: characters reserved for delimiting URLs.\n // We actually just auto-escape these.\n delims = ['<', '>', '\"', '`', ' ', '\\r', '\\n', '\\t'],\n\n // RFC 2396: characters not allowed for various reasons.\n unwise = ['{', '}', '|', '\\\\', '^', '`'].concat(delims),\n\n // Allowed by RFCs, but cause of XSS attacks. Always escape these.\n autoEscape = ['\\''].concat(unwise),\n // Characters that are never ever allowed in a hostname.\n // Note that any invalid chars are also handled, but these\n // are the ones that are *expected* to be seen, so we fast-path\n // them.\n nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),\n hostEndingChars = ['/', '?', '#'],\n hostnameMaxLen = 255,\n hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,\n hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,\n // protocols that can allow \"unsafe\" and \"unwise\" chars.\n unsafeProtocol = {\n 'javascript': true,\n 'javascript:': true\n },\n // protocols that never have a hostname.\n hostlessProtocol = {\n 'javascript': true,\n 'javascript:': true\n },\n // protocols that always contain a // bit.\n slashedProtocol = {\n 'http': true,\n 'https': true,\n 'ftp': true,\n 'gopher': true,\n 'file': true,\n 'http:': true,\n 'https:': true,\n 'ftp:': true,\n 'gopher:': true,\n 'file:': true\n },\n querystring = require('querystring');\n\nfunction urlParse(url, parseQueryString, slashesDenoteHost) {\n if (url && util.isObject(url) && url instanceof Url) return url;\n\n var u = new Url;\n u.parse(url, parseQueryString, slashesDenoteHost);\n return u;\n}\n\nUrl.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {\n if (!util.isString(url)) {\n throw new TypeError(\"Parameter 'url' must be a string, not \" + typeof url);\n }\n\n // Copy chrome, IE, opera backslash-handling behavior.\n // Back slashes before the query string get converted to forward slashes\n // See: https://code.google.com/p/chromium/issues/detail?id=25916\n var queryIndex = url.indexOf('?'),\n splitter =\n (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',\n uSplit = url.split(splitter),\n slashRegex = /\\\\/g;\n uSplit[0] = uSplit[0].replace(slashRegex, '/');\n url = uSplit.join(splitter);\n\n var rest = url;\n\n // trim before proceeding.\n // This is to support parse stuff like \" http://foo.com \\n\"\n rest = rest.trim();\n\n if (!slashesDenoteHost && url.split('#').length === 1) {\n // Try fast path regexp\n var simplePath = simplePathPattern.exec(rest);\n if (simplePath) {\n this.path = rest;\n this.href = rest;\n this.pathname = simplePath[1];\n if (simplePath[2]) {\n this.search = simplePath[2];\n if (parseQueryString) {\n this.query = querystring.parse(this.search.substr(1));\n Line truncated
|
||||
"'use strict';\n\nmodule.exports = {\n isString: function(arg) {\n return typeof(arg) === 'string';\n },\n isObject: function(arg) {\n return typeof(arg) === 'object' && arg !== null;\n },\n isNull: function(arg) {\n return arg === null;\n },\n isNullOrUndefined: function(arg) {\n return arg == null;\n }\n};\n",
|
||||
"/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// allow camelcase as these are things that go onto the wire\n/* eslint-disable camelcase */\n\nexport enum PushRuleActionName {\n DontNotify = \"dont_notify\",\n Notify = \"notify\",\n Coalesce = \"coalesce\",\n}\n\nexport enum TweakName {\n Highlight = \"highlight\",\n Sound = \"sound\",\n}\n\nexport type Tweak<N extends TweakName, V> = {\n set_tweak: N;\n value: V;\n};\n\nexport type TweakHighlight = Tweak<TweakName.Highlight, boolean>;\nexport type TweakSound = Tweak<TweakName.Sound, string>;\n\nexport type Tweaks = TweakHighlight | TweakSound;\n\nexport enum ConditionOperator {\n ExactEquals = \"==\",\n LessThan = \"<\",\n GreaterThan = \">\",\n GreaterThanOrEqual = \">=\",\n LessThanOrEqual = \"<=\",\n}\n\nexport type PushRuleAction = Tweaks | PushRuleActionName;\n\nexport type MemberCountCondition\n <N extends number, Op extends ConditionOperator = ConditionOperator.ExactEquals>\n = `${Op}${N}` | (Op extends ConditionOperator.ExactEquals ? `${N}` : never);\n\nexport type AnyMemberCountCondition = MemberCountCondition<number, ConditionOperator>;\n\nexport const DMMemberCountCondition: MemberCountCondition<2> = \"2\";\n\nexport function isDmMemberCountCondition(condition: AnyMemberCountCondition): boolean {\n return condition === \"==2\" || condition === \"2\";\n}\n\nexport enum ConditionKind {\n EventMatch = \"event_match\",\n ContainsDisplayName = \"contains_display_name\",\n RoomMemberCount = \"room_member_count\",\n SenderNotificationPermission = \"sender_notification_permission\",\n}\n\nexport interface IPushRuleCondition<N extends ConditionKind | string> {\n [k: string]: any; // for custom conditions, there can be other fields here\n kind: N;\n}\n\nexport interface IEventMatchCondition extends IPushRuleCondition<ConditionKind.EventMatch> {\n key: string;\n pattern: string;\n}\n\nexport interface IContainsDisplayNameCondition extends IPushRuleCondition<ConditionKind.ContainsDisplayName> {\n // no additional fields\n}\n\nexport interface IRoomMemberCountCondition extends IPushRuleCondition<ConditionKind.RoomMemberCount> {\n is: AnyMemberCountCondition;\n}\n\nexport interface ISenderNotificationPermissionCondition\n extends IPushRuleCondition<ConditionKind.SenderNotificationPermission> {\n key: string;\n}\n\nexport type PushRuleCondition = IPushRuleCondition<string>\n | IEventMatchCondition\n | IContainsDisplayNameCondition\n | IRoomMemberCountCondition\n | ISenderNotificationPermissionCondition;\n\nexport enum PushRuleKind {\n Override = \"override\",\n ContentSpecific = \"content\",\n RoomSpecific = \"room\",\n SenderSpecific = \"sender\",\n Underride = \"underride\",\n}\n\nexport enum RuleId {\n Master = \".m.rule.master\",\n ContainsDisplayName = \".m.rule.contains_display_name\",\n ContainsUserName = \".m.rule.contains_user_name\",\n AtRoomNotification = \".m.rule.roomnotif\",\n DM = \".m.rule.room_one_to_one\",\n EncryptedDM = \".m.rule.encrypted_room_one_to_one\",\n Message = \".m.rule.message\",\n EncryptedMessage = \".m.rule.encrypted\",\n InviteToSelf = \".m.rule.invite_for_me\",\n MemberEvent = \".m.rule.member_event\",\n IncomingCall = \".m.rule.call\",\n SuppressNotices = \".m.rule.suppress_notices\",\n Tombstone = \".m.rule.tombstone\",\n}\n\nexport type PushRuleSet = {\n [k in PushRuleKind]?: IPushRule[];\n};\n\nexport interface IPushRule {\n actions: PushRuleAction[];\n conditions?: PushRuleCondition[];\n default: boolean;\n enabled: boolean;\n pattern?: string;\n rule_id: RuleId | string;\n}\n\nexport interface IAnnotatedPushRule extends IPushRule {\n kind: PushRuleKind;\n}\n\nexport interface IPushRules {\n global: PushRuleSet;\n device?: PushRuleSet;\n}\n\nexport interface IPusher {\n app_display_name: string;\n app_id: string;\n data: {\n format?: string; // TODO: Types\n url?: string; // TODO: Required if kind==http\n brand?: string; // TODO: For email notifications only?\n };\n device_display_name: string;\n kind: string; // TODO: Types\n lang: string;\n profile_tag?: string;\n pushkey: string;\n}\n\nexport interface IPusherRequest extends IPusher {\n append?: boolean;\n}\n\n/* eslint-enable camelcase */\n",
|
||||
"/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// allow camelcase as these are things that go onto the wire\n/* eslint-disable camelcase */\n\nexport enum PushRuleActionName {\n DontNotify = \"dont_notify\",\n Notify = \"notify\",\n Coalesce = \"coalesce\",\n}\n\nexport enum TweakName {\n Highlight = \"highlight\",\n Sound = \"sound\",\n}\n\nexport type Tweak<N extends TweakName, V> = {\n set_tweak: N;\n value: V;\n};\n\nexport type TweakHighlight = Tweak<TweakName.Highlight, boolean>;\nexport type TweakSound = Tweak<TweakName.Sound, string>;\n\nexport type Tweaks = TweakHighlight | TweakSound;\n\nexport enum ConditionOperator {\n ExactEquals = \"==\",\n LessThan = \"<\",\n GreaterThan = \">\",\n GreaterThanOrEqual = \">=\",\n LessThanOrEqual = \"<=\",\n}\n\nexport type PushRuleAction = Tweaks | PushRuleActionName;\n\nexport type MemberCountCondition\n <N extends number, Op extends ConditionOperator = ConditionOperator.ExactEquals>\n = `${Op}${N}` | (Op extends ConditionOperator.ExactEquals ? `${N}` : never);\n\nexport type AnyMemberCountCondition = MemberCountCondition<number, ConditionOperator>;\n\nexport const DMMemberCountCondition: MemberCountCondition<2> = \"2\";\n\nexport function isDmMemberCountCondition(condition: AnyMemberCountCondition): boolean {\n return condition === \"==2\" || condition === \"2\";\n}\n\nexport enum ConditionKind {\n EventMatch = \"event_match\",\n ContainsDisplayName = \"contains_display_name\",\n RoomMemberCount = \"room_member_count\",\n SenderNotificationPermission = \"sender_notification_permission\",\n}\n\nexport interface IPushRuleCondition<N extends ConditionKind | string> {\n [k: string]: any; // for custom conditions, there can be other fields here\n kind: N;\n}\n\nexport interface IEventMatchCondition extends IPushRuleCondition<ConditionKind.EventMatch> {\n key: string;\n pattern: string;\n}\n\nexport interface IContainsDisplayNameCondition extends IPushRuleCondition<ConditionKind.ContainsDisplayName> {\n // no additional fields\n}\n\nexport interface IRoomMemberCountCondition extends IPushRuleCondition<ConditionKind.RoomMemberCount> {\n is: AnyMemberCountCondition;\n}\n\nexport interface ISenderNotificationPermissionCondition\n extends IPushRuleCondition<ConditionKind.SenderNotificationPermission> {\n key: string;\n}\n\n// XXX: custom conditions are possible but always fail, and break the typescript discriminated union so ignore them here\n// IPushRuleCondition<Exclude<string, ConditionKind>> unfortunately does not resolve this at the time of writing.\nexport type PushRuleCondition = IEventMatchCondition\n | IContainsDisplayNameCondition\n | IRoomMemberCountCondition\n | ISenderNotificationPermissionCondition;\n\nexport enum PushRuleKind {\n Override = \"override\",\n ContentSpecific = \"content\",\n RoomSpecific = \"room\",\n SenderSpecific = \"sender\",\n Underride = \"underride\",\n}\n\nexport enum RuleId {\n Master = \".m.rule.master\",\n ContainsDisplayName = \".m.rule.contains_display_name\",\n ContainsUserName = \".m.rule.contains_user_name\",\n AtRoomNotification = \".m.rule.roomnotif\",\n DM = \".m.rule.room_one_to_one\",\n EncryptedDM = \".m.rule.encrypted_room_one_to_one\",\n Message = \".m.rule.message\",\n EncryptedMessage = \".m.rule.encrypted\",\n InviteToSelf = \".m.rule.invite_for_me\",\n MemberEvent = \".m.rule.member_event\",\n IncomingCall = \".m.rule.call\",\n SuppressNotices = \".m.rule.suppress_notices\",\n Tombstone = \".m.rule.tombstone\",\n}\n\nexport type PushRuleSet = {\n [k in PushRuleKind]?: IPushRule[];\n};\n\nexport interface IPushRule {\n actions: PushRuleAction[];\n conditions?: PushRuleCondition[];\n default: boolean;\n enabled: boolean;\n pattern?: string;\n rule_id: RuleId | string;\n}\n\nexport interface IAnnotatedPushRule extends IPushRule {\n kind: PushRuleKind;\n}\n\nexport interface IPushRules {\n global: PushRuleSet;\n device?: PushRuleSet;\n}\n\nexport interface IPusher {\n app_display_name: string;\n app_id: string;\n data: {\n format?: string; // TODO: Types\n url?: string; // TODO: Required if kind==http\n brand?: string; // TODO: For email notifications only?\n };\n device_display_name: string;\n kind: string; // TODO: Types\n lang: string;\n profile_tag?Line truncated
|
||||
"/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { UnstableValue } from \"../NamespacedValue\";\n\nexport enum EventType {\n // Room state events\n RoomCanonicalAlias = \"m.room.canonical_alias\",\n RoomCreate = \"m.room.create\",\n RoomJoinRules = \"m.room.join_rules\",\n RoomMember = \"m.room.member\",\n RoomThirdPartyInvite = \"m.room.third_party_invite\",\n RoomPowerLevels = \"m.room.power_levels\",\n RoomName = \"m.room.name\",\n RoomTopic = \"m.room.topic\",\n RoomAvatar = \"m.room.avatar\",\n RoomPinnedEvents = \"m.room.pinned_events\",\n RoomEncryption = \"m.room.encryption\",\n RoomHistoryVisibility = \"m.room.history_visibility\",\n RoomGuestAccess = \"m.room.guest_access\",\n RoomServerAcl = \"m.room.server_acl\",\n RoomTombstone = \"m.room.tombstone\",\n /**\n * @deprecated Should not be used.\n */\n RoomAliases = \"m.room.aliases\", // deprecated https://matrix.org/docs/spec/client_server/r0.6.1#historical-events\n\n SpaceChild = \"m.space.child\",\n SpaceParent = \"m.space.parent\",\n\n // Room timeline events\n RoomRedaction = \"m.room.redaction\",\n RoomMessage = \"m.room.message\",\n RoomMessageEncrypted = \"m.room.encrypted\",\n Sticker = \"m.sticker\",\n CallInvite = \"m.call.invite\",\n CallCandidates = \"m.call.candidates\",\n CallAnswer = \"m.call.answer\",\n CallHangup = \"m.call.hangup\",\n CallReject = \"m.call.reject\",\n CallSelectAnswer = \"m.call.select_answer\",\n CallNegotiate = \"m.call.negotiate\",\n CallSDPStreamMetadataChanged = \"m.call.sdp_stream_metadata_changed\",\n CallSDPStreamMetadataChangedPrefix = \"org.matrix.call.sdp_stream_metadata_changed\",\n CallReplaces = \"m.call.replaces\",\n CallAssertedIdentity = \"m.call.asserted_identity\",\n CallAssertedIdentityPrefix = \"org.matrix.call.asserted_identity\",\n KeyVerificationRequest = \"m.key.verification.request\",\n KeyVerificationStart = \"m.key.verification.start\",\n KeyVerificationCancel = \"m.key.verification.cancel\",\n KeyVerificationMac = \"m.key.verification.mac\",\n KeyVerificationDone = \"m.key.verification.done\",\n // use of this is discouraged https://matrix.org/docs/spec/client_server/r0.6.1#m-room-message-feedback\n RoomMessageFeedback = \"m.room.message.feedback\",\n Reaction = \"m.reaction\",\n\n // Room ephemeral events\n Typing = \"m.typing\",\n Receipt = \"m.receipt\",\n Presence = \"m.presence\",\n\n // Room account_data events\n FullyRead = \"m.fully_read\",\n Tag = \"m.tag\",\n SpaceOrder = \"org.matrix.msc3230.space_order\", // MSC3230\n\n // User account_data events\n PushRules = \"m.push_rules\",\n Direct = \"m.direct\",\n IgnoredUserList = \"m.ignored_user_list\",\n\n // to_device events\n RoomKey = \"m.room_key\",\n RoomKeyRequest = \"m.room_key_request\",\n ForwardedRoomKey = \"m.forwarded_room_key\",\n Dummy = \"m.dummy\",\n}\n\nexport enum RelationType {\n Annotation = \"m.annotation\",\n Replace = \"m.replace\",\n}\n\nexport enum MsgType {\n Text = \"m.text\",\n Emote = \"m.emote\",\n Notice = \"m.notice\",\n Image = \"m.image\",\n File = \"m.file\",\n Audio = \"m.audio\",\n Location = \"m.location\",\n Video = \"m.video\",\n}\n\nexport const RoomCreateTypeField = \"type\";\n\nexport enum RoomType {\n Space = \"m.space\",\n}\n\n/**\n * Identifier for an [MSC3088](https://github.com/matrix-org/matrix-doc/pull/3088)\n * room purpose. Note that this reference is UNSTABLE and subject to breaking changes,\n * including its eventual removal.\n */\nexport const UNSTABLE_MSC3088_PURPOSE = new UnstableValue(\"m.room.purpose\", \"org.matrix.msc3088.purpose\");\n\n/**\n * Enabled flag for an [MSC3088](https://github.com/matrix-org/matrix-doc/pull/3088)\n * room purpose. Note that this reference is UNSTABLE and subject to breaking changes,\n * including its eventual removal.\n */\nexport const UNSTABLE_MSC3088_ENABLED = new UnstableValue(\"m.enabled\", \"org.matrix.msc3088.enabled\");\n\n/**\n * Subtype for an [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room.\n * Note that this reference is UNSTABLE and subject to breaking changes, including its\n * eventual removal.\n */\nexport const UNSTABLE_MSC3089_TREE_SUBTYPE = new UnstableValue(\"m.data_tree\", \"org.matrix.msc3089.data_tree\");\n\n/**\n Line truncated
|
||||
"/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport interface IImageInfo {\n size?: number;\n mimetype?: string;\n thumbnail_info?: { // eslint-disable-line camelcase\n w?: number;\n h?: number;\n size?: number;\n mimetype?: string;\n };\n w?: number;\n h?: number;\n}\n\nexport enum Visibility {\n Public = \"public\",\n Private = \"private\",\n}\n\nexport enum Preset {\n PrivateChat = \"private_chat\",\n TrustedPrivateChat = \"trusted_private_chat\",\n PublicChat = \"public_chat\",\n}\n\nexport type ResizeMethod = \"crop\" | \"scale\";\n\n// TODO move to http-api after TSification\nexport interface IAbortablePromise<T> extends Promise<T> {\n abort(): void;\n}\n\nexport type IdServerUnbindResult = \"no-support\" | \"success\";\n\n// Knock and private are reserved keywords which are not yet implemented.\nexport enum JoinRule {\n Public = \"public\",\n Invite = \"invite\",\n /**\n * @deprecated Reserved keyword. Should not be used. Not yet implemented.\n */\n Private = \"private\",\n Knock = \"knock\", // MSC2403 - only valid inside experimental room versions at this time.\n Restricted = \"restricted\", // MSC3083 - only valid inside experimental room versions at this time.\n}\n\nexport enum RestrictedAllowType {\n RoomMembership = \"m.room_membership\", // MSC3083 - only valid inside experimental room versions at this time.\n}\n\nexport enum GuestAccess {\n CanJoin = \"can_join\",\n Forbidden = \"forbidden\",\n}\n\nexport enum HistoryVisibility {\n Invited = \"invited\",\n Joined = \"joined\",\n Shared = \"shared\",\n WorldReadable = \"world_readable\",\n}\n\n// XXX move to OlmDevice when converted\nexport interface InboundGroupSessionData {\n room_id: string; // eslint-disable-line camelcase\n session: string;\n keysClaimed: Record<string, string>;\n forwardingCurve25519KeyChain: string[];\n}\n",
|
||||
"/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// Types relating to the /search API\n\nimport { IRoomEvent, IStateEvent } from \"../sync-accumulator\";\nimport { IRoomEventFilter } from \"../filter\";\nimport { SearchResult } from \"../models/search-result\";\n\n/* eslint-disable camelcase */\nexport interface IEventWithRoomId extends IRoomEvent {\n room_id: string;\n}\n\nexport interface IStateEventWithRoomId extends IStateEvent {\n room_id: string;\n}\n\nexport interface IMatrixProfile {\n avatar_url?: string;\n displayname?: string;\n}\n\nexport interface IResultContext {\n events_before: IEventWithRoomId[];\n events_after: IEventWithRoomId[];\n profile_info: Record<string, IMatrixProfile>;\n start?: string;\n end?: string;\n}\n\nexport interface ISearchResult {\n rank: number;\n result: IEventWithRoomId;\n context: IResultContext;\n}\n\nenum GroupKey {\n RoomId = \"room_id\",\n Sender = \"sender\",\n}\n\nexport interface IResultRoomEvents {\n count: number;\n highlights: string[];\n results: ISearchResult[];\n state?: { [roomId: string]: IStateEventWithRoomId[] };\n groups?: {\n [groupKey in GroupKey]: {\n [value: string]: {\n next_batch?: string;\n order: number;\n results: string[];\n };\n };\n };\n next_batch?: string;\n}\n\ninterface IResultCategories {\n room_events: IResultRoomEvents;\n}\n\nexport type SearchKey = \"content.body\" | \"content.name\" | \"content.topic\";\n\nexport enum SearchOrderBy {\n Recent = \"recent\",\n Rank = \"rank\",\n}\n\nexport interface ISearchRequestBody {\n search_categories: {\n room_events: {\n search_term: string;\n keys?: SearchKey[];\n filter?: IRoomEventFilter;\n order_by?: SearchOrderBy;\n event_context?: {\n before_limit?: number;\n after_limit?: number;\n include_profile?: boolean;\n };\n include_state?: boolean;\n groupings?: {\n group_by: {\n key: GroupKey;\n }[];\n };\n };\n };\n}\n\nexport interface ISearchResponse {\n search_categories: IResultCategories;\n}\n\nexport interface ISearchResults {\n _query?: ISearchRequestBody;\n results: SearchResult[];\n highlights: string[];\n count?: number;\n next_batch?: string;\n pendingRequest?: Promise<ISearchResults>;\n}\n/* eslint-enable camelcase */\n",
|
||||
@@ -237,12 +238,12 @@
|
||||
"/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations Ltd\nCopyright 2017 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventEmitter } from \"events\";\n\nexport class ReEmitter {\n private target: EventEmitter;\n\n constructor(target: EventEmitter) {\n this.target = target;\n }\n\n reEmit(source: EventEmitter, eventNames: string[]) {\n for (const eventName of eventNames) {\n // We include the source as the last argument for event handlers which may need it,\n // such as read receipt listeners on the client class which won't have the context\n // of the room.\n const forSource = (...args) => {\n // EventEmitter special cases 'error' to make the emit function throw if no\n // handler is attached, which sort of makes sense for making sure that something\n // handles an error, but for re-emitting, there could be a listener on the original\n // source object so the test doesn't really work. We *could* try to replicate the\n // same logic and throw if there is no listener on either the source or the target,\n // but this behaviour is fairly undesireable for us anyway: the main place we throw\n // 'error' events is for calls, where error events are usually emitted some time\n // later by a different part of the code where 'emit' throwing because the app hasn't\n // added an error handler isn't terribly helpful. (A better fix in retrospect may\n // have been to just avoid using the event name 'error', but backwards compat...)\n if (eventName === 'error' && this.target.listenerCount('error') === 0) return;\n this.target.emit(eventName, ...args, source);\n };\n source.on(eventName, forSource);\n }\n }\n}\n",
|
||||
"/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/** @module auto-discovery */\n\nimport { logger } from './logger';\nimport { URL as NodeURL } from \"url\";\n\n// Dev note: Auto discovery is part of the spec.\n// See: https://matrix.org/docs/spec/client_server/r0.4.0.html#server-discovery\n\n/**\n * Description for what an automatically discovered client configuration\n * would look like. Although this is a class, it is recommended that it\n * be treated as an interface definition rather than as a class.\n *\n * Additional properties than those defined here may be present, and\n * should follow the Java package naming convention.\n */\nclass DiscoveredClientConfig { // eslint-disable-line no-unused-vars\n // Dev note: this is basically a copy/paste of the .well-known response\n // object as defined in the spec. It does have additional information,\n // however. Overall, this exists to serve as a place for documentation\n // and not functionality.\n // See https://matrix.org/docs/spec/client_server/r0.4.0.html#get-well-known-matrix-client\n\n constructor() {\n /**\n * The homeserver configuration the client should use. This will\n * always be present on the object.\n * @type {{state: string, base_url: string}} The configuration.\n */\n this[\"m.homeserver\"] = {\n /**\n * The lookup result state. If this is anything other than\n * AutoDiscovery.SUCCESS then base_url may be falsey. Additionally,\n * if this is not AutoDiscovery.SUCCESS then the client should\n * assume the other properties in the client config (such as\n * the identity server configuration) are not valid.\n */\n state: AutoDiscovery.PROMPT,\n\n /**\n * If the state is AutoDiscovery.FAIL_ERROR or .FAIL_PROMPT\n * then this will contain a human-readable (English) message\n * for what went wrong. If the state is none of those previously\n * mentioned, this will be falsey.\n */\n error: \"Something went wrong\",\n\n /**\n * The base URL clients should use to talk to the homeserver,\n * particularly for the login process. May be falsey if the\n * state is not AutoDiscovery.SUCCESS.\n */\n base_url: \"https://matrix.org\",\n };\n\n /**\n * The identity server configuration the client should use. This\n * will always be present on teh object.\n * @type {{state: string, base_url: string}} The configuration.\n */\n this[\"m.identity_server\"] = {\n /**\n * The lookup result state. If this is anything other than\n * AutoDiscovery.SUCCESS then base_url may be falsey.\n */\n state: AutoDiscovery.PROMPT,\n\n /**\n * The base URL clients should use for interacting with the\n * identity server. May be falsey if the state is not\n * AutoDiscovery.SUCCESS.\n */\n base_url: \"https://vector.im\",\n };\n }\n}\n\n/**\n * Utilities for automatically discovery resources, such as homeservers\n * for users to log in to.\n */\nexport class AutoDiscovery {\n // Dev note: the constants defined here are related to but not\n // exactly the same as those in the spec. This is to hopefully\n // translate the meaning of the states in the spec, but also\n // support our own if needed.\n\n static get ERROR_INVALID() {\n return \"Invalid homeserver discovery response\";\n }\n\n static get ERROR_GENERIC_FAILURE() {\n return \"Failed to get autodiscovery configuration from server\";\n }\n\n static get ERROR_INVALID_HS_BASE_URL() {\n return \"Invalid base_url for m.homeserver\";\n }\n\n static get ERROR_INVALID_HOMESERVER() {\n return \"Homeserver URL does not appear to be a valid Matrix homeserver\";\n }\n\n static get ERROR_INVALID_IS_BASE_URL() {\n return \"Invalid base_url for m.identity_server\";\n }\n\n static get ERROR_INVALID_IDENTITY_SERVER() {\n return \"Identity server URL does not appear to be a valid identity server\";\n }\n\n static get ERROR_INVALID_IS() {\n return \"Invalid identity server discoverLine truncated
|
||||
"/*\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport * as matrixcs from \"./matrix\";\nimport request from \"browser-request\";\nimport queryString from \"qs\";\n\nmatrixcs.request(function(opts, fn) {\n // We manually fix the query string for browser-request because\n // it doesn't correctly handle cases like ?via=one&via=two. Instead\n // we mimic `request`'s query string interface to make it all work\n // as expected.\n // browser-request will happily take the constructed string as the\n // query string without trying to modify it further.\n opts.qs = queryString.stringify(opts.qs || {}, opts.qsStringifyOptions);\n return request(opts, fn);\n});\n\n// just *accessing* indexedDB throws an exception in firefox with\n// indexeddb disabled.\nlet indexedDB;\ntry {\n indexedDB = global.indexedDB;\n} catch (e) {}\n\n// if our browser (appears to) support indexeddb, use an indexeddb crypto store.\nif (indexedDB) {\n matrixcs.setCryptoStoreFactory(\n function() {\n return new matrixcs.IndexedDBCryptoStore(\n indexedDB, \"matrix-js-sdk:crypto\",\n );\n },\n );\n}\n\n// We export 3 things to make browserify happy as well as downstream projects.\n// It's awkward, but required.\nexport * from \"./matrix\";\nexport default matrixcs; // keep export for browserify package deps\nglobal.matrixcs = matrixcs;\n",
|
||||
"/*\nCopyright 2015-2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MatrixClient} for the public class.\n * @module client\n */\n\nimport { EventEmitter } from \"events\";\nimport { ISyncStateData, SyncApi } from \"./sync\";\nimport { EventStatus, IContent, IDecryptOptions, IEvent, MatrixEvent } from \"./models/event\";\nimport { StubStore } from \"./store/stub\";\nimport { createNewMatrixCall, MatrixCall, ConstraintsType, getUserMediaContraints } from \"./webrtc/call\";\nimport { Filter, IFilterDefinition } from \"./filter\";\nimport { CallEventHandler } from './webrtc/callEventHandler';\nimport * as utils from './utils';\nimport { sleep } from './utils';\nimport { Group } from \"./models/group\";\nimport { Direction, EventTimeline } from \"./models/event-timeline\";\nimport { PushAction, PushProcessor } from \"./pushprocessor\";\nimport { AutoDiscovery } from \"./autodiscovery\";\nimport * as olmlib from \"./crypto/olmlib\";\nimport { decodeBase64, encodeBase64 } from \"./crypto/olmlib\";\nimport { ReEmitter } from './ReEmitter';\nimport { IRoomEncryption, RoomList } from './crypto/RoomList';\nimport { logger } from './logger';\nimport { SERVICE_TYPES } from './service-types';\nimport {\n MatrixError,\n MatrixHttpApi,\n PREFIX_IDENTITY_V2,\n PREFIX_MEDIA_R0,\n PREFIX_R0,\n PREFIX_UNSTABLE,\n retryNetworkOperation,\n} from \"./http-api\";\nimport {\n Crypto,\n fixBackupKey,\n IBootstrapCrossSigningOpts,\n ICheckOwnCrossSigningTrustOpts,\n IMegolmSessionData,\n isCryptoAvailable,\n VerificationMethod,\n} from './crypto';\nimport { DeviceInfo, IDevice } from \"./crypto/deviceinfo\";\nimport { decodeRecoveryKey } from './crypto/recoverykey';\nimport { keyFromAuthData } from './crypto/key_passphrase';\nimport { User } from \"./models/user\";\nimport { getHttpUriForMxc } from \"./content-repo\";\nimport { SearchResult } from \"./models/search-result\";\nimport {\n DEHYDRATION_ALGORITHM,\n IDehydratedDevice,\n IDehydratedDeviceKeyInfo,\n IDeviceKeys,\n IOneTimeKey,\n} from \"./crypto/dehydration\";\nimport {\n IKeyBackupInfo,\n IKeyBackupPrepareOpts,\n IKeyBackupRestoreOpts,\n IKeyBackupRestoreResult,\n IKeyBackupSession,\n} from \"./crypto/keybackup\";\nimport { IIdentityServerProvider } from \"./@types/IIdentityServerProvider\";\nimport type Request from \"request\";\nimport { MatrixScheduler } from \"./scheduler\";\nimport { ICryptoCallbacks, IMinimalEvent, IRoomEvent, IStateEvent, NotificationCountType } from \"./matrix\";\nimport {\n CrossSigningKey,\n IAddSecretStorageKeyOpts,\n ICreateSecretStorageOpts,\n IEncryptedEventInfo,\n IImportRoomKeysOpts,\n IRecoveryKey,\n ISecretStorageKeyInfo,\n} from \"./crypto/api\";\nimport { SyncState } from \"./sync.api\";\nimport { EventTimelineSet } from \"./models/event-timeline-set\";\nimport { VerificationRequest } from \"./crypto/verification/request/VerificationRequest\";\nimport { Base as Verification } from \"./crypto/verification/Base\";\nimport * as ContentHelpers from \"./content-helpers\";\nimport { CrossSigningInfo, DeviceTrustLevel, ICacheCallbacks, UserTrustLevel } from \"./crypto/CrossSigning\";\nimport { Room } from \"./models/room\";\nimport {\n IAddThreePidOnlyBody,\n IBindThreePidBody,\n ICreateRoomOpts,\n IEventSearchOpts,\n IGuestAccessOpts,\n IJoinRoomOpts,\n IPaginateOpts,\n IPresenceOpts,\n IRedactOpts,\n IRoomDirectoryOptions,\n ISearchOpts,\n ISendEventResponse,\n IUploadOpts,\n} from \"./@types/requests\";\nimport {\n EventType,\n MsgType,\n RelationType,\n RoomCreateTypeField,\n RoomType,\n UNSTABLE_MSC3088_ENABLED,\n UNSTABLE_MSC3088_PURPOSE,\n UNSTABLE_MSC3089_TREE_SUBTYPE,\n} from \"./@types/event\";\nimport { IAbortablePromise, IdServerUnbindResult, IImageInfo, Preset, Visibility } from \"./@types/partials\";\nimport { EventMapper, eventMapperFor, MapperOpts } from \"./event-mapper\";\nimport { randomString } from \"./randomstring\";\nimport { ReadStream } from \"fs\";\nimport { WebStorageSessionStore } from \"./store/session/webstorage\";\nimport { BackupManager, IKeyBackup, IKeyBackupCheck, IPreparedKeyBackupVersion, TrustInfo } from \"./crypto/backup\";\nimport { DEFAULT_TREE_POWER_LEVELS_TEMPLATE, MSC3089TreeSpace } from \"./models/MSC3089TreeSpace\";\nimport { ISignatures } from \"./@types/signed\";\niLine truncated
|
||||
"/*\nCopyright 2015-2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MatrixClient} for the public class.\n * @module client\n */\n\nimport { EventEmitter } from \"events\";\nimport { ISyncStateData, SyncApi } from \"./sync\";\nimport { EventStatus, IContent, IDecryptOptions, IEvent, MatrixEvent } from \"./models/event\";\nimport { StubStore } from \"./store/stub\";\nimport { createNewMatrixCall, MatrixCall, ConstraintsType, getUserMediaContraints } from \"./webrtc/call\";\nimport { Filter, IFilterDefinition } from \"./filter\";\nimport { CallEventHandler } from './webrtc/callEventHandler';\nimport * as utils from './utils';\nimport { sleep } from './utils';\nimport { Group } from \"./models/group\";\nimport { Direction, EventTimeline } from \"./models/event-timeline\";\nimport { IActionsObject, PushProcessor } from \"./pushprocessor\";\nimport { AutoDiscovery } from \"./autodiscovery\";\nimport * as olmlib from \"./crypto/olmlib\";\nimport { decodeBase64, encodeBase64 } from \"./crypto/olmlib\";\nimport { ReEmitter } from './ReEmitter';\nimport { IRoomEncryption, RoomList } from './crypto/RoomList';\nimport { logger } from './logger';\nimport { SERVICE_TYPES } from './service-types';\nimport {\n MatrixError,\n MatrixHttpApi,\n PREFIX_IDENTITY_V2,\n PREFIX_MEDIA_R0,\n PREFIX_R0,\n PREFIX_UNSTABLE,\n retryNetworkOperation,\n} from \"./http-api\";\nimport {\n Crypto,\n fixBackupKey,\n IBootstrapCrossSigningOpts,\n ICheckOwnCrossSigningTrustOpts,\n IMegolmSessionData,\n isCryptoAvailable,\n VerificationMethod,\n} from './crypto';\nimport { DeviceInfo, IDevice } from \"./crypto/deviceinfo\";\nimport { decodeRecoveryKey } from './crypto/recoverykey';\nimport { keyFromAuthData } from './crypto/key_passphrase';\nimport { User } from \"./models/user\";\nimport { getHttpUriForMxc } from \"./content-repo\";\nimport { SearchResult } from \"./models/search-result\";\nimport {\n DEHYDRATION_ALGORITHM,\n IDehydratedDevice,\n IDehydratedDeviceKeyInfo,\n IDeviceKeys,\n IOneTimeKey,\n} from \"./crypto/dehydration\";\nimport {\n IKeyBackupInfo,\n IKeyBackupPrepareOpts,\n IKeyBackupRestoreOpts,\n IKeyBackupRestoreResult,\n IKeyBackupSession,\n} from \"./crypto/keybackup\";\nimport { IIdentityServerProvider } from \"./@types/IIdentityServerProvider\";\nimport type Request from \"request\";\nimport { MatrixScheduler } from \"./scheduler\";\nimport { ICryptoCallbacks, IMinimalEvent, IRoomEvent, IStateEvent, NotificationCountType } from \"./matrix\";\nimport {\n CrossSigningKey,\n IAddSecretStorageKeyOpts,\n ICreateSecretStorageOpts,\n IEncryptedEventInfo,\n IImportRoomKeysOpts,\n IRecoveryKey,\n ISecretStorageKeyInfo,\n} from \"./crypto/api\";\nimport { SyncState } from \"./sync.api\";\nimport { EventTimelineSet } from \"./models/event-timeline-set\";\nimport { VerificationRequest } from \"./crypto/verification/request/VerificationRequest\";\nimport { Base as Verification } from \"./crypto/verification/Base\";\nimport * as ContentHelpers from \"./content-helpers\";\nimport { CrossSigningInfo, DeviceTrustLevel, ICacheCallbacks, UserTrustLevel } from \"./crypto/CrossSigning\";\nimport { Room } from \"./models/room\";\nimport {\n IAddThreePidOnlyBody,\n IBindThreePidBody,\n ICreateRoomOpts,\n IEventSearchOpts,\n IGuestAccessOpts,\n IJoinRoomOpts,\n IPaginateOpts,\n IPresenceOpts,\n IRedactOpts,\n IRoomDirectoryOptions,\n ISearchOpts,\n ISendEventResponse,\n IUploadOpts,\n} from \"./@types/requests\";\nimport {\n EventType,\n MsgType,\n RelationType,\n RoomCreateTypeField,\n RoomType,\n UNSTABLE_MSC3088_ENABLED,\n UNSTABLE_MSC3088_PURPOSE,\n UNSTABLE_MSC3089_TREE_SUBTYPE,\n} from \"./@types/event\";\nimport { IAbortablePromise, IdServerUnbindResult, IImageInfo, Preset, Visibility } from \"./@types/partials\";\nimport { EventMapper, eventMapperFor, MapperOpts } from \"./event-mapper\";\nimport { randomString } from \"./randomstring\";\nimport { ReadStream } from \"fs\";\nimport { WebStorageSessionStore } from \"./store/session/webstorage\";\nimport { BackupManager, IKeyBackup, IKeyBackupCheck, IPreparedKeyBackupVersion, TrustInfo } from \"./crypto/backup\";\nimport { DEFAULT_TREE_POWER_LEVELS_TEMPLATE, MSC3089TreeSpace } from \"./models/MSC3089TreeSpace\";\nimport { ISignatures } from \"./@types/signed\"Line truncated
|
||||
"/*\nCopyright 2018 New Vector Ltd\nCopyright 2018 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/** @module ContentHelpers */\n\nimport { MsgType } from \"./@types/event\";\n\n/**\n * Generates the content for a HTML Message event\n * @param {string} body the plaintext body of the message\n * @param {string} htmlBody the HTML representation of the message\n * @returns {{msgtype: string, format: string, body: string, formatted_body: string}}\n */\nexport function makeHtmlMessage(body: string, htmlBody: string) {\n return {\n msgtype: MsgType.Text,\n format: \"org.matrix.custom.html\",\n body: body,\n formatted_body: htmlBody,\n };\n}\n\n/**\n * Generates the content for a HTML Notice event\n * @param {string} body the plaintext body of the notice\n * @param {string} htmlBody the HTML representation of the notice\n * @returns {{msgtype: string, format: string, body: string, formatted_body: string}}\n */\nexport function makeHtmlNotice(body: string, htmlBody: string) {\n return {\n msgtype: MsgType.Notice,\n format: \"org.matrix.custom.html\",\n body: body,\n formatted_body: htmlBody,\n };\n}\n\n/**\n * Generates the content for a HTML Emote event\n * @param {string} body the plaintext body of the emote\n * @param {string} htmlBody the HTML representation of the emote\n * @returns {{msgtype: string, format: string, body: string, formatted_body: string}}\n */\nexport function makeHtmlEmote(body: string, htmlBody: string) {\n return {\n msgtype: MsgType.Emote,\n format: \"org.matrix.custom.html\",\n body: body,\n formatted_body: htmlBody,\n };\n}\n\n/**\n * Generates the content for a Plaintext Message event\n * @param {string} body the plaintext body of the emote\n * @returns {{msgtype: string, body: string}}\n */\nexport function makeTextMessage(body: string) {\n return {\n msgtype: MsgType.Text,\n body: body,\n };\n}\n\n/**\n * Generates the content for a Plaintext Notice event\n * @param {string} body the plaintext body of the notice\n * @returns {{msgtype: string, body: string}}\n */\nexport function makeNotice(body: string) {\n return {\n msgtype: MsgType.Notice,\n body: body,\n };\n}\n\n/**\n * Generates the content for a Plaintext Emote event\n * @param {string} body the plaintext body of the emote\n * @returns {{msgtype: string, body: string}}\n */\nexport function makeEmoteMessage(body: string) {\n return {\n msgtype: MsgType.Emote,\n body: body,\n };\n}\n",
|
||||
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n/**\n * @module content-repo\n */\n\nimport * as utils from \"./utils\";\n\n/**\n * Get the HTTP URL for an MXC URI.\n * @param {string} baseUrl The base homeserver url which has a content repo.\n * @param {string} mxc The mxc:// URI.\n * @param {Number} width The desired width of the thumbnail.\n * @param {Number} height The desired height of the thumbnail.\n * @param {string} resizeMethod The thumbnail resize method to use, either\n * \"crop\" or \"scale\".\n * @param {Boolean} allowDirectLinks If true, return any non-mxc URLs\n * directly. Fetching such URLs will leak information about the user to\n * anyone they share a room with. If false, will return the emptry string\n * for such URLs.\n * @return {string} The complete URL to the content.\n */\nexport function getHttpUriForMxc(\n baseUrl: string,\n mxc: string,\n width: number,\n height: number,\n resizeMethod: string,\n allowDirectLinks = false,\n): string {\n if (typeof mxc !== \"string\" || !mxc) {\n return '';\n }\n if (mxc.indexOf(\"mxc://\") !== 0) {\n if (allowDirectLinks) {\n return mxc;\n } else {\n return '';\n }\n }\n let serverAndMediaId = mxc.slice(6); // strips mxc://\n let prefix = \"/_matrix/media/r0/download/\";\n const params = {};\n\n if (width) {\n params[\"width\"] = Math.round(width);\n }\n if (height) {\n params[\"height\"] = Math.round(height);\n }\n if (resizeMethod) {\n params[\"method\"] = resizeMethod;\n }\n if (Object.keys(params).length > 0) {\n // these are thumbnailing params so they probably want the\n // thumbnailing API...\n prefix = \"/_matrix/media/r0/thumbnail/\";\n }\n\n const fragmentOffset = serverAndMediaId.indexOf(\"#\");\n let fragment = \"\";\n if (fragmentOffset >= 0) {\n fragment = serverAndMediaId.substr(fragmentOffset);\n serverAndMediaId = serverAndMediaId.substr(0, fragmentOffset);\n }\n\n const urlParams = (Object.keys(params).length === 0 ? \"\" : (\"?\" + utils.encodeParams(params)));\n return baseUrl + prefix + serverAndMediaId + urlParams + fragment;\n}\n",
|
||||
"/*\nCopyright 2019 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Cross signing methods\n * @module crypto/CrossSigning\n */\n\nimport { EventEmitter } from 'events';\n\nimport { decodeBase64, encodeBase64, pkSign, pkVerify } from './olmlib';\nimport { logger } from '../logger';\nimport { IndexedDBCryptoStore } from '../crypto/store/indexeddb-crypto-store';\nimport { decryptAES, encryptAES } from './aes';\nimport { PkSigning } from \"@matrix-org/olm\";\nimport { DeviceInfo } from \"./deviceinfo\";\nimport { SecretStorage } from \"./SecretStorage\";\nimport { ICrossSigningKey, ISignedKey, MatrixClient } from \"../client\";\nimport { OlmDevice } from \"./OlmDevice\";\nimport { ICryptoCallbacks } from \"../matrix\";\nimport { ISignatures } from \"../@types/signed\";\nimport { CryptoStore } from \"./store/base\";\n\nconst KEY_REQUEST_TIMEOUT_MS = 1000 * 60;\n\nfunction publicKeyFromKeyInfo(keyInfo: ICrossSigningKey): string {\n // `keys` is an object with { [`ed25519:${pubKey}`]: pubKey }\n // We assume only a single key, and we want the bare form without type\n // prefix, so we select the values.\n return Object.values(keyInfo.keys)[0];\n}\n\nexport interface ICacheCallbacks {\n getCrossSigningKeyCache?(type: string, expectedPublicKey?: string): Promise<Uint8Array>;\n storeCrossSigningKeyCache?(type: string, key: Uint8Array): Promise<void>;\n}\n\nexport interface ICrossSigningInfo {\n keys: Record<string, ICrossSigningKey>;\n firstUse: boolean;\n crossSigningVerifiedBefore: boolean;\n}\n\nexport class CrossSigningInfo extends EventEmitter {\n public keys: Record<string, ICrossSigningKey> = {};\n public firstUse = true;\n // This tracks whether we've ever verified this user with any identity.\n // When you verify a user, any devices online at the time that receive\n // the verifying signature via the homeserver will latch this to true\n // and can use it in the future to detect cases where the user has\n // become unverified later for any reason.\n private crossSigningVerifiedBefore = false;\n\n /**\n * Information about a user's cross-signing keys\n *\n * @class\n *\n * @param {string} userId the user that the information is about\n * @param {object} callbacks Callbacks used to interact with the app\n * Requires getCrossSigningKey and saveCrossSigningKeys\n * @param {object} cacheCallbacks Callbacks used to interact with the cache\n */\n constructor(\n public readonly userId: string,\n private callbacks: ICryptoCallbacks = {},\n private cacheCallbacks: ICacheCallbacks = {},\n ) {\n super();\n }\n\n public static fromStorage(obj: ICrossSigningInfo, userId: string): CrossSigningInfo {\n const res = new CrossSigningInfo(userId);\n for (const prop in obj) {\n if (obj.hasOwnProperty(prop)) {\n res[prop] = obj[prop];\n }\n }\n return res;\n }\n\n public toStorage(): ICrossSigningInfo {\n return {\n keys: this.keys,\n firstUse: this.firstUse,\n crossSigningVerifiedBefore: this.crossSigningVerifiedBefore,\n };\n }\n\n /**\n * Calls the app callback to ask for a private key\n *\n * @param {string} type The key type (\"master\", \"self_signing\", or \"user_signing\")\n * @param {string} expectedPubkey The matching public key or undefined to use\n * the stored public key for the given key type.\n * @returns {Array} An array with [ public key, Olm.PkSigning ]\n */\n public async getCrossSigningKey(type: string, expectedPubkey?: string): Promise<[string, PkSigning]> {\n const shouldCache = [\"master\", \"self_signing\", \"user_signing\"].indexOf(type) >= 0;\n\n if (!this.callbacks.getCrossSigningKey) {\n throw new Error(\"No getCrossSigningKey callback supplied\");\n }\n\n if (expectedPubkey === undefined) {\n expectedPubkey = this.getId(type);\n }\n\n function validateKey(key: Uint8Array): [string, PkSigning] {\n if (!key) return;\n const signing = new global.Olm.PkSigning();\n const gotPubkey = signing.init_with_seed(key);\n if (gotPubkey === expectedPubkey) {\n return [gotPubkey, signing];\n }\n signing.free();\n }\n\n let privkey;\Line truncated
|
||||
"/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module crypto/DeviceList\n *\n * Manages the list of other users' devices\n */\n\nimport { EventEmitter } from 'events';\n\nimport { logger } from '../logger';\nimport { DeviceInfo, IDevice } from './deviceinfo';\nimport { CrossSigningInfo, ICrossSigningInfo } from './CrossSigning';\nimport * as olmlib from './olmlib';\nimport { IndexedDBCryptoStore } from './store/indexeddb-crypto-store';\nimport { chunkPromises, defer, IDeferred, sleep } from '../utils';\nimport { MatrixClient } from \"../client\";\nimport { OlmDevice } from \"./OlmDevice\";\nimport { CryptoStore } from \"./store/base\";\n\n/* State transition diagram for DeviceList.deviceTrackingStatus\n *\n * |\n * stopTrackingDeviceList V\n * +---------------------> NOT_TRACKED\n * | |\n * +<--------------------+ | startTrackingDeviceList\n * | | V\n * | +-------------> PENDING_DOWNLOAD <--------------------+-+\n * | | ^ | | |\n * | | restart download | | start download | | invalidateUserDeviceList\n * | | client failed | | | |\n * | | | V | |\n * | +------------ DOWNLOAD_IN_PROGRESS -------------------+ |\n * | | | |\n * +<-------------------+ | download successful |\n * ^ V |\n * +----------------------- UP_TO_DATE ------------------------+\n */\n\n// constants for DeviceList.deviceTrackingStatus\nexport enum TrackingStatus {\n NotTracked,\n PendingDownload,\n DownloadInProgress,\n UpToDate,\n}\n\nexport type DeviceInfoMap = Record<string, Record<string, DeviceInfo>>;\n\n/**\n * @alias module:crypto/DeviceList\n */\nexport class DeviceList extends EventEmitter {\n private devices: { [userId: string]: { [deviceId: string]: IDevice } } = {};\n\n public crossSigningInfo: { [userId: string]: ICrossSigningInfo } = {};\n\n // map of identity keys to the user who owns it\n private userByIdentityKey: Record<string, string> = {};\n\n // which users we are tracking device status for.\n private deviceTrackingStatus: { [userId: string]: TrackingStatus } = {}; // loaded from storage in load()\n\n // The 'next_batch' sync token at the point the data was written,\n // ie. a token representing the point immediately after the\n // moment represented by the snapshot in the db.\n private syncToken: string = null;\n\n private keyDownloadsInProgressByUser: { [userId: string]: Promise<void> } = {};\n\n // Set whenever changes are made other than setting the sync token\n private dirty = false;\n\n // Promise resolved when device data is saved\n private savePromise: Promise<boolean> = null;\n // Function that resolves the save promise\n private resolveSavePromise: (saved: boolean) => void = null;\n // The time the save is scheduled for\n private savePromiseTime: number = null;\n // The timer used to delay the save\n private saveTimer: number = null;\n // True if we have fetched data from the server or loaded a non-empty\n // set of device data from the store\n private hasFetched: boolean = null;\n\n private readonly serialiser: DeviceListUpdateSerialiser;\n\n constructor(\n baseApis: MatrixClient,\n private readonly cryptoStore: CryptoStore,\n olmDevice: OlmDevice,\n // Maximum number of user IDs per request to prevent server overload (#1619)\n public readonly keyDownloadChunkSize = 250,\n ) {\n super();\n\n this.serialiser = new DeviceListUpdateSerialiser(baseApis, olmDevice, this);\n }\n\n /**\n * Load the device tracking state from storage\n */\n public async load() {\n await this.cryptoStore.doTxn(\n 'readonly', [IndexedDBCryptoStore.STORE_DEVICE_DATA], (txn) => {\n this.cryptoStore.getEndToEndDeviceData(txn, (deviceData) => {\n this.hasFetched = Boolean(deviceData && deviceData.devices);\n this.devices = deviceData ? deviceData.devices : {},\n this.crossSigningInfo = deviceData ?\n deviceData.Line truncated
|
||||
"/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from \"../logger\";\nimport { MatrixEvent } from \"../models/event\";\nimport { EventEmitter } from \"events\";\nimport { createCryptoStoreCacheCallbacks, ICacheCallbacks } from \"./CrossSigning\";\nimport { IndexedDBCryptoStore } from './store/indexeddb-crypto-store';\nimport { PREFIX_UNSTABLE } from \"../http-api\";\nimport { Crypto, IBootstrapCrossSigningOpts } from \"./index\";\nimport {\n CrossSigningKeys,\n ICrossSigningKey,\n ICryptoCallbacks,\n ISignedKey,\n KeySignatures,\n} from \"../matrix\";\nimport { ISecretStorageKeyInfo } from \"./api\";\nimport { IKeyBackupInfo } from \"./keybackup\";\n\ninterface ICrossSigningKeys {\n authUpload: IBootstrapCrossSigningOpts[\"authUploadDeviceSigningKeys\"];\n keys: Record<string, ICrossSigningKey>;\n}\n\n/**\n * Builds an EncryptionSetupOperation by calling any of the add.. methods.\n * Once done, `buildOperation()` can be called which allows to apply to operation.\n *\n * This is used as a helper by Crypto to keep track of all the network requests\n * and other side-effects of bootstrapping, so it can be applied in one go (and retried in the future)\n * Also keeps track of all the private keys created during bootstrapping, so we don't need to prompt for them\n * more than once.\n */\nexport class EncryptionSetupBuilder {\n public readonly accountDataClientAdapter: AccountDataClientAdapter;\n public readonly crossSigningCallbacks: CrossSigningCallbacks;\n public readonly ssssCryptoCallbacks: SSSSCryptoCallbacks;\n\n private crossSigningKeys: ICrossSigningKeys = null;\n private keySignatures: KeySignatures = null;\n private keyBackupInfo: IKeyBackupInfo = null;\n private sessionBackupPrivateKey: Uint8Array;\n\n /**\n * @param {Object.<String, MatrixEvent>} accountData pre-existing account data, will only be read, not written.\n * @param {CryptoCallbacks} delegateCryptoCallbacks crypto callbacks to delegate to if the key isn't in cache yet\n */\n constructor(accountData: Record<string, MatrixEvent>, delegateCryptoCallbacks: ICryptoCallbacks) {\n this.accountDataClientAdapter = new AccountDataClientAdapter(accountData);\n this.crossSigningCallbacks = new CrossSigningCallbacks();\n this.ssssCryptoCallbacks = new SSSSCryptoCallbacks(delegateCryptoCallbacks);\n }\n\n /**\n * Adds new cross-signing public keys\n *\n * @param {function} authUpload Function called to await an interactive auth\n * flow when uploading device signing keys.\n * Args:\n * {function} A function that makes the request requiring auth. Receives\n * the auth data as an object. Can be called multiple times, first with\n * an empty authDict, to obtain the flows.\n * @param {Object} keys the new keys\n */\n public addCrossSigningKeys(authUpload: ICrossSigningKeys[\"authUpload\"], keys: ICrossSigningKeys[\"keys\"]): void {\n this.crossSigningKeys = { authUpload, keys };\n }\n\n /**\n * Adds the key backup info to be updated on the server\n *\n * Used either to create a new key backup, or add signatures\n * from the new MSK.\n *\n * @param {Object} keyBackupInfo as received from/sent to the server\n */\n public addSessionBackup(keyBackupInfo: IKeyBackupInfo): void {\n this.keyBackupInfo = keyBackupInfo;\n }\n\n /**\n * Adds the session backup private key to be updated in the local cache\n *\n * Used after fixing the format of the key\n *\n * @param {Uint8Array} privateKey\n */\n public addSessionBackupPrivateKeyToCache(privateKey: Uint8Array): void {\n this.sessionBackupPrivateKey = privateKey;\n }\n\n /**\n * Add signatures from a given user and device/x-sign key\n * Used to sign the new cross-signing key with the device key\n *\n * @param {String} userId\n * @param {String} deviceId\n * @param {Object} signature\n */\n public addKeySignature(userId: string, deviceId: string, signature: ISignedKey): void {\n if (!this.keySignatures) {\n this.keySignatures = {};\n }\n const userSignatures = this.keySignatures[userId] || {};\n this.keySignatures[userId] = userSignatures;\n userSignatures[deviceId] = signature;\n }\n\n /**\n * @param {String} type\n * @param {ObjecLine truncated
|
||||
"/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from \"../logger\";\nimport { MatrixEvent } from \"../models/event\";\nimport { EventEmitter } from \"events\";\nimport { createCryptoStoreCacheCallbacks, ICacheCallbacks } from \"./CrossSigning\";\nimport { IndexedDBCryptoStore } from './store/indexeddb-crypto-store';\nimport { PREFIX_UNSTABLE } from \"../http-api\";\nimport { Crypto, IBootstrapCrossSigningOpts } from \"./index\";\nimport {\n CrossSigningKeys,\n ICrossSigningKey,\n ICryptoCallbacks,\n ISignedKey,\n KeySignatures,\n} from \"../matrix\";\nimport { ISecretStorageKeyInfo } from \"./api\";\nimport { IKeyBackupInfo } from \"./keybackup\";\n\ninterface ICrossSigningKeys {\n authUpload: IBootstrapCrossSigningOpts[\"authUploadDeviceSigningKeys\"];\n keys: Record<string, ICrossSigningKey>;\n}\n\n/**\n * Builds an EncryptionSetupOperation by calling any of the add.. methods.\n * Once done, `buildOperation()` can be called which allows to apply to operation.\n *\n * This is used as a helper by Crypto to keep track of all the network requests\n * and other side-effects of bootstrapping, so it can be applied in one go (and retried in the future)\n * Also keeps track of all the private keys created during bootstrapping, so we don't need to prompt for them\n * more than once.\n */\nexport class EncryptionSetupBuilder {\n public readonly accountDataClientAdapter: AccountDataClientAdapter;\n public readonly crossSigningCallbacks: CrossSigningCallbacks;\n public readonly ssssCryptoCallbacks: SSSSCryptoCallbacks;\n\n private crossSigningKeys: ICrossSigningKeys = null;\n private keySignatures: KeySignatures = null;\n private keyBackupInfo: IKeyBackupInfo = null;\n private sessionBackupPrivateKey: Uint8Array;\n\n /**\n * @param {Object.<String, MatrixEvent>} accountData pre-existing account data, will only be read, not written.\n * @param {CryptoCallbacks} delegateCryptoCallbacks crypto callbacks to delegate to if the key isn't in cache yet\n */\n constructor(accountData: Record<string, MatrixEvent>, delegateCryptoCallbacks?: ICryptoCallbacks) {\n this.accountDataClientAdapter = new AccountDataClientAdapter(accountData);\n this.crossSigningCallbacks = new CrossSigningCallbacks();\n this.ssssCryptoCallbacks = new SSSSCryptoCallbacks(delegateCryptoCallbacks);\n }\n\n /**\n * Adds new cross-signing public keys\n *\n * @param {function} authUpload Function called to await an interactive auth\n * flow when uploading device signing keys.\n * Args:\n * {function} A function that makes the request requiring auth. Receives\n * the auth data as an object. Can be called multiple times, first with\n * an empty authDict, to obtain the flows.\n * @param {Object} keys the new keys\n */\n public addCrossSigningKeys(authUpload: ICrossSigningKeys[\"authUpload\"], keys: ICrossSigningKeys[\"keys\"]): void {\n this.crossSigningKeys = { authUpload, keys };\n }\n\n /**\n * Adds the key backup info to be updated on the server\n *\n * Used either to create a new key backup, or add signatures\n * from the new MSK.\n *\n * @param {Object} keyBackupInfo as received from/sent to the server\n */\n public addSessionBackup(keyBackupInfo: IKeyBackupInfo): void {\n this.keyBackupInfo = keyBackupInfo;\n }\n\n /**\n * Adds the session backup private key to be updated in the local cache\n *\n * Used after fixing the format of the key\n *\n * @param {Uint8Array} privateKey\n */\n public addSessionBackupPrivateKeyToCache(privateKey: Uint8Array): void {\n this.sessionBackupPrivateKey = privateKey;\n }\n\n /**\n * Add signatures from a given user and device/x-sign key\n * Used to sign the new cross-signing key with the device key\n *\n * @param {String} userId\n * @param {String} deviceId\n * @param {Object} signature\n */\n public addKeySignature(userId: string, deviceId: string, signature: ISignedKey): void {\n if (!this.keySignatures) {\n this.keySignatures = {};\n }\n const userSignatures = this.keySignatures[userId] || {};\n this.keySignatures[userId] = userSignatures;\n userSignatures[deviceId] = signature;\n }\n\n /**\n * @param {String} type\n * @param {ObjeLine truncated
|
||||
"/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2017, 2019 New Vector Ltd\nCopyright 2019, 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from '../logger';\nimport { IndexedDBCryptoStore } from './store/indexeddb-crypto-store';\nimport * as algorithms from './algorithms';\n\n// The maximum size of an event is 65K, and we base64 the content, so this is a\n// reasonable approximation to the biggest plaintext we can encrypt.\nconst MAX_PLAINTEXT_LENGTH = 65536 * 3 / 4;\n\nfunction checkPayloadLength(payloadString) {\n if (payloadString === undefined) {\n throw new Error(\"payloadString undefined\");\n }\n\n if (payloadString.length > MAX_PLAINTEXT_LENGTH) {\n // might as well fail early here rather than letting the olm library throw\n // a cryptic memory allocation error.\n //\n // Note that even if we manage to do the encryption, the message send may fail,\n // because by the time we've wrapped the ciphertext in the event object, it may\n // exceed 65K. But at least we won't just fail with \"abort()\" in that case.\n const err = new Error(\"Message too long (\" + payloadString.length + \" bytes). \" +\n \"The maximum for an encrypted message is \" +\n MAX_PLAINTEXT_LENGTH + \" bytes.\");\n // TODO: [TypeScript] We should have our own error types\n err.data = {\n errcode: \"M_TOO_LARGE\",\n error: \"Payload too large for encrypted message\",\n };\n throw err;\n }\n}\n\n/**\n * The type of object we use for importing and exporting megolm session data.\n *\n * @typedef {Object} module:crypto/OlmDevice.MegolmSessionData\n * @property {String} sender_key Sender's Curve25519 device key\n * @property {String[]} forwarding_curve25519_key_chain Devices which forwarded\n * this session to us (normally empty).\n * @property {Object<string, string>} sender_claimed_keys Other keys the sender claims.\n * @property {String} room_id Room this session is used in\n * @property {String} session_id Unique id for the session\n * @property {String} session_key Base64'ed key data\n */\n\n/**\n * Manages the olm cryptography functions. Each OlmDevice has a single\n * OlmAccount and a number of OlmSessions.\n *\n * Accounts and sessions are kept pickled in the cryptoStore.\n *\n * @constructor\n * @alias module:crypto/OlmDevice\n *\n * @param {Object} cryptoStore A store for crypto data\n *\n * @property {string} deviceCurve25519Key Curve25519 key for the account\n * @property {string} deviceEd25519Key Ed25519 key for the account\n */\nexport function OlmDevice(cryptoStore) {\n this._cryptoStore = cryptoStore;\n this._pickleKey = \"DEFAULT_KEY\";\n\n // don't know these until we load the account from storage in init()\n this.deviceCurve25519Key = null;\n this.deviceEd25519Key = null;\n this._maxOneTimeKeys = null;\n\n // we don't bother stashing outboundgroupsessions in the cryptoStore -\n // instead we keep them here.\n this._outboundGroupSessionStore = {};\n\n // Store a set of decrypted message indexes for each group session.\n // This partially mitigates a replay attack where a MITM resends a group\n // message into the room.\n //\n // When we decrypt a message and the message index matches a previously\n // decrypted message, one possible cause of that is that we are decrypting\n // the same event, and may not indicate an actual replay attack. For\n // example, this could happen if we receive events, forget about them, and\n // then re-fetch them when we backfill. So we store the event ID and\n // timestamp corresponding to each message index when we first decrypt it,\n // and compare these against the event ID and timestamp every time we use\n // that same index. If they match, then we're probably decrypting the same\n // event and we don't consider it a replay attack.\n //\n // Keys are strings of form \"<senderKey>|<session_id>|<message_index>\"\n // Values are objects of the form \"{id: <event id>, timestamp: <ts>}\"\n this._inboundGroupSessionMessageIndexes = {};\n\n // Keep track of sessions that we're starting, so that we don't start\n // multiple sessions for the same device at the same time.\n this._sessionsInProgress = {};\n\n // Used by olm to serialise prekey message decryptions\n this._olmPrekeyLine truncated
|
||||
"/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from '../logger';\nimport { MatrixClient } from \"../client\";\nimport { IRoomKeyRequestBody, IRoomKeyRequestRecipient } from \"./index\";\nimport { CryptoStore, OutgoingRoomKeyRequest } from './store/base';\nimport { EventType } from \"../@types/event\";\n\n/**\n * Internal module. Management of outgoing room key requests.\n *\n * See https://docs.google.com/document/d/1m4gQkcnJkxNuBmb5NoFCIadIY-DyqqNAS3lloE73BlQ\n * for draft documentation on what we're supposed to be implementing here.\n *\n * @module\n */\n\n// delay between deciding we want some keys, and sending out the request, to\n// allow for (a) it turning up anyway, (b) grouping requests together\nconst SEND_KEY_REQUESTS_DELAY_MS = 500;\n\n/** possible states for a room key request\n *\n * The state machine looks like:\n *\n * | (cancellation sent)\n * | .-------------------------------------------------.\n * | | |\n * V V (cancellation requested) |\n * UNSENT -----------------------------+ |\n * | | |\n * | | |\n * | (send successful) | CANCELLATION_PENDING_AND_WILL_RESEND\n * V | Λ\n * SENT | |\n * |-------------------------------- | --------------'\n * | | (cancellation requested with intent\n * | | to resend the original request)\n * | |\n * | (cancellation requested) |\n * V |\n * CANCELLATION_PENDING |\n * | |\n * | (cancellation sent) |\n * V |\n * (deleted) <---------------------------+\n *\n * @enum {number}\n */\nexport enum RoomKeyRequestState {\n /** request not yet sent */\n Unsent,\n /** request sent, awaiting reply */\n Sent,\n /** reply received, cancellation not yet sent */\n CancellationPending,\n /**\n * Cancellation not yet sent and will transition to UNSENT instead of\n * being deleted once the cancellation has been sent.\n */\n CancellationPendingAndWillResend,\n}\n\nexport class OutgoingRoomKeyRequestManager {\n // handle for the delayed call to sendOutgoingRoomKeyRequests. Non-null\n // if the callback has been set, or if it is still running.\n private sendOutgoingRoomKeyRequestsTimer: number = null;\n\n // sanity check to ensure that we don't end up with two concurrent runs\n // of sendOutgoingRoomKeyRequests\n private sendOutgoingRoomKeyRequestsRunning = false;\n\n private clientRunning = false;\n\n constructor(\n private readonly baseApis: MatrixClient,\n private readonly deviceId: string,\n private readonly cryptoStore: CryptoStore,\n ) {}\n\n /**\n * Called when the client is started. Sets background processes running.\n */\n public start(): void {\n this.clientRunning = true;\n }\n\n /**\n * Called when the client is stopped. Stops any running background processes.\n */\n public stop(): void {\n logger.log('stopping OutgoingRoomKeyRequestManager');\n // stop the timer on the next run\n this.clientRunning = false;\n }\n\n /**\n * Send any requests that have been queued\n */\n public sendQueuedRequests(): void {\n this.startTimer();\n }\n\n /**\n * Queue up a room key request, if we haven't already queued or sent one.\n *\n * The `requestBody` is compared (with a deep-equality check) against\n * previous queued or sent requests and if it matches, no change is made.\n * Otherwise, a request is added to the pending list, and a job is started\n * in the background to send it.\n *\n * @param {module:crypto~RoomKeyRequestBody} requestBody\n * @param {Array<{userId: string, deviceId: string}>} recipients\n * @param {boolean} resend whether to resend the key request if there is\n * already one\n *\n * @returns {Promise} resolves when the request has been added to the\n * Line truncated
|
||||
"/*\nCopyright 2018 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module crypto/RoomList\n *\n * Manages the list of encrypted rooms\n */\n\nimport { CryptoStore } from './store/base';\nimport { IndexedDBCryptoStore } from './store/indexeddb-crypto-store';\n\n/* eslint-disable camelcase */\nexport interface IRoomEncryption {\n algorithm: string;\n rotation_period_ms?: number;\n rotation_period_msgs?: number;\n}\n/* eslint-enable camelcase */\n\n/**\n * @alias module:crypto/RoomList\n */\nexport class RoomList {\n // Object of roomId -> room e2e info object (body of the m.room.encryption event)\n private roomEncryption: Record<string, IRoomEncryption> = {};\n\n constructor(private readonly cryptoStore: CryptoStore) {}\n\n public async init(): Promise<void> {\n await this.cryptoStore.doTxn(\n 'readwrite', [IndexedDBCryptoStore.STORE_ROOMS], (txn) => {\n this.cryptoStore.getEndToEndRooms(txn, (result) => {\n this.roomEncryption = result;\n });\n },\n );\n }\n\n public getRoomEncryption(roomId: string): IRoomEncryption {\n return this.roomEncryption[roomId] || null;\n }\n\n public isRoomEncrypted(roomId: string): boolean {\n return Boolean(this.getRoomEncryption(roomId));\n }\n\n public async setRoomEncryption(roomId: string, roomInfo: IRoomEncryption): Promise<void> {\n // important that this happens before calling into the store\n // as it prevents the Crypto::setRoomEncryption from calling\n // this twice for consecutive m.room.encryption events\n this.roomEncryption[roomId] = roomInfo;\n await this.cryptoStore.doTxn(\n 'readwrite', [IndexedDBCryptoStore.STORE_ROOMS], (txn) => {\n this.cryptoStore.storeEndToEndRoom(roomId, roomInfo, txn);\n },\n );\n }\n}\n",
|
||||
@@ -270,7 +271,7 @@
|
||||
"/*\nCopyright 2018 New Vector Ltd\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * QR code key verification.\n * @module crypto/verification/QRCode\n */\n\nimport { VerificationBase as Base } from \"./Base\";\nimport {\n newKeyMismatchError,\n newUserCancelledError,\n} from './Error';\nimport { encodeUnpaddedBase64, decodeBase64 } from \"../olmlib\";\nimport { logger } from '../../logger';\n\nexport const SHOW_QR_CODE_METHOD = \"m.qr_code.show.v1\";\nexport const SCAN_QR_CODE_METHOD = \"m.qr_code.scan.v1\";\n\n/**\n * @class crypto/verification/QRCode/ReciprocateQRCode\n * @extends {module:crypto/verification/Base}\n */\nexport class ReciprocateQRCode extends Base {\n static factory(...args) {\n return new ReciprocateQRCode(...args);\n }\n\n static get NAME() {\n return \"m.reciprocate.v1\";\n }\n\n async _doVerification() {\n if (!this.startEvent) {\n // TODO: Support scanning QR codes\n throw new Error(\"It is not currently possible to start verification\" +\n \"with this method yet.\");\n }\n\n const { qrCodeData } = this.request;\n // 1. check the secret\n if (this.startEvent.getContent()['secret'] !== qrCodeData.encodedSharedSecret) {\n throw newKeyMismatchError();\n }\n\n // 2. ask if other user shows shield as well\n await new Promise((resolve, reject) => {\n this.reciprocateQREvent = {\n confirm: resolve,\n cancel: () => reject(newUserCancelledError()),\n };\n this.emit(\"show_reciprocate_qr\", this.reciprocateQREvent);\n });\n\n // 3. determine key to sign / mark as trusted\n const keys = {};\n\n switch (qrCodeData.mode) {\n case MODE_VERIFY_OTHER_USER: {\n // add master key to keys to be signed, only if we're not doing self-verification\n const masterKey = qrCodeData.otherUserMasterKey;\n keys[`ed25519:${masterKey}`] = masterKey;\n break;\n }\n case MODE_VERIFY_SELF_TRUSTED: {\n const deviceId = this.request.targetDevice.deviceId;\n keys[`ed25519:${deviceId}`] = qrCodeData.otherDeviceKey;\n break;\n }\n case MODE_VERIFY_SELF_UNTRUSTED: {\n const masterKey = qrCodeData.myMasterKey;\n keys[`ed25519:${masterKey}`] = masterKey;\n break;\n }\n }\n\n // 4. sign the key (or mark own MSK as verified in case of MODE_VERIFY_SELF_TRUSTED)\n await this._verifyKeys(this.userId, keys, (keyId, device, keyInfo) => {\n // make sure the device has the expected keys\n const targetKey = keys[keyId];\n if (!targetKey) throw newKeyMismatchError();\n\n if (keyInfo !== targetKey) {\n logger.error(\"key ID from key info does not match\");\n throw newKeyMismatchError();\n }\n for (const deviceKeyId in device.keys) {\n if (!deviceKeyId.startsWith(\"ed25519\")) continue;\n const deviceTargetKey = keys[deviceKeyId];\n if (!deviceTargetKey) throw newKeyMismatchError();\n if (device.keys[deviceKeyId] !== deviceTargetKey) {\n logger.error(\"master key does not match\");\n throw newKeyMismatchError();\n }\n }\n });\n }\n}\n\nconst CODE_VERSION = 0x02; // the version of binary QR codes we support\nconst BINARY_PREFIX = \"MATRIX\"; // ASCII, used to prefix the binary format\nconst MODE_VERIFY_OTHER_USER = 0x00; // Verifying someone who isn't us\nconst MODE_VERIFY_SELF_TRUSTED = 0x01; // We trust the master key\nconst MODE_VERIFY_SELF_UNTRUSTED = 0x02; // We do not trust the master key\n\nexport class QRCodeData {\n constructor(\n mode, sharedSecret, otherUserMasterKey,\n otherDeviceKey, myMasterKey, buffer,\n ) {\n this._sharedSecret = sharedSecret;\n this._mode = mode;\n this._otherUserMasterKey = otherUserMasterKey;\n this._otherDeviceKey = otherDeviceKey;\n this._myMasterKey = myMasterKey;\n this._buffer = buffer;\n }\n\n static async create(request, client) {\n const sharedSecret = QRCodeData._generateSharedSecret();\n Line truncated
|
||||
"/*\nCopyright 2018 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Short Authentication String (SAS) verification.\n * @module crypto/verification/SAS\n */\n\nimport { VerificationBase as Base, SwitchStartEventError } from \"./Base\";\nimport anotherjson from 'another-json';\nimport {\n errorFactory,\n newInvalidMessageError,\n newKeyMismatchError,\n newUnknownMethodError,\n newUserCancelledError,\n} from './Error';\nimport { logger } from '../../logger';\n\nconst START_TYPE = \"m.key.verification.start\";\n\nconst EVENTS = [\n \"m.key.verification.accept\",\n \"m.key.verification.key\",\n \"m.key.verification.mac\",\n];\n\nlet olmutil;\n\nconst newMismatchedSASError = errorFactory(\n \"m.mismatched_sas\", \"Mismatched short authentication string\",\n);\n\nconst newMismatchedCommitmentError = errorFactory(\n \"m.mismatched_commitment\", \"Mismatched commitment\",\n);\n\nfunction generateDecimalSas(sasBytes) {\n /**\n * +--------+--------+--------+--------+--------+\n * | Byte 0 | Byte 1 | Byte 2 | Byte 3 | Byte 4 |\n * +--------+--------+--------+--------+--------+\n * bits: 87654321 87654321 87654321 87654321 87654321\n * \\____________/\\_____________/\\____________/\n * 1st number 2nd number 3rd number\n */\n return [\n (sasBytes[0] << 5 | sasBytes[1] >> 3) + 1000,\n ((sasBytes[1] & 0x7) << 10 | sasBytes[2] << 2 | sasBytes[3] >> 6) + 1000,\n ((sasBytes[3] & 0x3f) << 7 | sasBytes[4] >> 1) + 1000,\n ];\n}\n\nconst emojiMapping = [\n [\"🐶\", \"dog\"], // 0\n [\"🐱\", \"cat\"], // 1\n [\"🦁\", \"lion\"], // 2\n [\"🐎\", \"horse\"], // 3\n [\"🦄\", \"unicorn\"], // 4\n [\"🐷\", \"pig\"], // 5\n [\"🐘\", \"elephant\"], // 6\n [\"🐰\", \"rabbit\"], // 7\n [\"🐼\", \"panda\"], // 8\n [\"🐓\", \"rooster\"], // 9\n [\"🐧\", \"penguin\"], // 10\n [\"🐢\", \"turtle\"], // 11\n [\"🐟\", \"fish\"], // 12\n [\"🐙\", \"octopus\"], // 13\n [\"🦋\", \"butterfly\"], // 14\n [\"🌷\", \"flower\"], // 15\n [\"🌳\", \"tree\"], // 16\n [\"🌵\", \"cactus\"], // 17\n [\"🍄\", \"mushroom\"], // 18\n [\"🌏\", \"globe\"], // 19\n [\"🌙\", \"moon\"], // 20\n [\"☁️\", \"cloud\"], // 21\n [\"🔥\", \"fire\"], // 22\n [\"🍌\", \"banana\"], // 23\n [\"🍎\", \"apple\"], // 24\n [\"🍓\", \"strawberry\"], // 25\n [\"🌽\", \"corn\"], // 26\n [\"🍕\", \"pizza\"], // 27\n [\"🎂\", \"cake\"], // 28\n [\"❤️\", \"heart\"], // 29\n [\"🙂\", \"smiley\"], // 30\n [\"🤖\", \"robot\"], // 31\n [\"🎩\", \"hat\"], // 32\n [\"👓\", \"glasses\"], // 33\n [\"🔧\", \"spanner\"], // 34\n [\"🎅\", \"santa\"], // 35\n [\"👍\", \"thumbs up\"], // 36\n [\"☂️\", \"umbrella\"], // 37\n [\"⌛\", \"hourglass\"], // 38\n [\"⏰\", \"clock\"], // 39\n [\"🎁\", \"gift\"], // 40\n [\"💡\", \"light bulb\"], // 41\n [\"📕\", \"book\"], // 42\n [\"✏️\", \"pencil\"], // 43\n [\"📎\", \"paperclip\"], // 44\n [\"✂️\", \"scissors\"], // 45\n [\"🔒\", \"lock\"], // 46\n [\"🔑\", \"key\"], // 47\n [\"🔨\", \"hammer\"], // 48\n [\"☎️\", \"telephone\"], // 49\n [\"🏁\", \"flag\"], // 50\n [\"🚂\", \"train\"], // 51\n [\"🚲\", \"bicycle\"], // 52\n [\"✈️\", \"aeroplane\"], // 53\n [\"🚀\", \"rocket\"], // 54\n [\"🏆\", \"trophy\"], // 55\n [\"⚽\", \"ball\"], // 56\n [\"🎸\", \"guitar\"], // 57\n [\"🎺\", \"trumpet\"], // 58\n [\"🔔\", \"bell\"], // 59\n [\"⚓️\", \"anchor\"], // 60\n [\"🎧\", \"headphones\"], // 61\n [\"📁\", \"folder\"], // 62\n [\"📌\", \"pin\"], // 63\n];\n\nfunction generateEmojiSas(sasBytes) {\n const emojis = [\n // just like base64 encoding\n sasBytes[0] >> 2,\n (sasBytes[0] & 0x3) << 4 | sasBytes[1] >> 4,\n (sasBytes[1] & 0xf) << 2 | sasBytes[2] >> 6,\n sasBytes[2] & 0x3f,\n sasBytes[3] >> 2,\n (sasBytes[3] & 0x3) << 4 | sasBytes[4] >> 4,\n (sasBytes[4] & 0Line truncated
|
||||
"/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {\n VerificationRequest,\n REQUEST_TYPE,\n READY_TYPE,\n START_TYPE,\n} from \"./VerificationRequest\";\nimport { logger } from '../../../logger';\n\nconst MESSAGE_TYPE = \"m.room.message\";\nconst M_REFERENCE = \"m.reference\";\nconst M_RELATES_TO = \"m.relates_to\";\n\n/**\n * A key verification channel that sends verification events in the timeline of a room.\n * Uses the event id of the initial m.key.verification.request event as a transaction id.\n */\nexport class InRoomChannel {\n /**\n * @param {MatrixClient} client the matrix client, to send messages with and get current user & device from.\n * @param {string} roomId id of the room where verification events should be posted in, should be a DM with the given user.\n * @param {string} userId id of user that the verification request is directed at, should be present in the room.\n */\n constructor(client, roomId, userId = null) {\n this._client = client;\n this._roomId = roomId;\n this.userId = userId;\n this._requestEventId = null;\n }\n\n get receiveStartFromOtherDevices() {\n return true;\n }\n\n get roomId() {\n return this._roomId;\n }\n\n /** The transaction id generated/used by this verification channel */\n get transactionId() {\n return this._requestEventId;\n }\n\n static getOtherPartyUserId(event, client) {\n const type = InRoomChannel.getEventType(event);\n if (type !== REQUEST_TYPE) {\n return;\n }\n const ownUserId = client.getUserId();\n const sender = event.getSender();\n const content = event.getContent();\n const receiver = content.to;\n\n if (sender === ownUserId) {\n return receiver;\n } else if (receiver === ownUserId) {\n return sender;\n }\n }\n\n /**\n * @param {MatrixEvent} event the event to get the timestamp of\n * @return {number} the timestamp when the event was sent\n */\n getTimestamp(event) {\n return event.getTs();\n }\n\n /**\n * Checks whether the given event type should be allowed to initiate a new VerificationRequest over this channel\n * @param {string} type the event type to check\n * @returns {bool} boolean flag\n */\n static canCreateRequest(type) {\n return type === REQUEST_TYPE;\n }\n\n /**\n * Extract the transaction id used by a given key verification event, if any\n * @param {MatrixEvent} event the event\n * @returns {string} the transaction id\n */\n static getTransactionId(event) {\n if (InRoomChannel.getEventType(event) === REQUEST_TYPE) {\n return event.getId();\n } else {\n const relation = event.getRelation();\n if (relation && relation.rel_type === M_REFERENCE) {\n return relation.event_id;\n }\n }\n }\n\n /**\n * Checks whether this event is a well-formed key verification event.\n * This only does checks that don't rely on the current state of a potentially already channel\n * so we can prevent channels being created by invalid events.\n * `handleEvent` can do more checks and choose to ignore invalid events.\n * @param {MatrixEvent} event the event to validate\n * @param {MatrixClient} client the client to get the current user and device id from\n * @returns {bool} whether the event is valid and should be passed to handleEvent\n */\n static validateEvent(event, client) {\n const txnId = InRoomChannel.getTransactionId(event);\n if (typeof txnId !== \"string\" || txnId.length === 0) {\n return false;\n }\n const type = InRoomChannel.getEventType(event);\n const content = event.getContent();\n\n // from here on we're fairly sure that this is supposed to be\n // part of a verification request, so be noisy when rejecting something\n if (type === REQUEST_TYPE) {\n if (!content || typeof content.to !== \"string\" || !content.to.length) {\n logger.log(\"InRoomChannel: validateEvent: \" +\n \"no valid to \" + (content && content.to));\n return false;\n }\n\n // ignore requests that are not direct to or sent by the synciLine truncated
|
||||
"/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { randomString } from '../../../randomstring';\nimport { logger } from '../../../logger';\nimport {\n CANCEL_TYPE,\n PHASE_STARTED,\n PHASE_READY,\n REQUEST_TYPE,\n READY_TYPE,\n START_TYPE,\n VerificationRequest,\n} from \"./VerificationRequest\";\nimport { errorFromEvent, newUnexpectedMessageError } from \"../Error\";\nimport { MatrixEvent } from \"../../../models/event\";\n\n/**\n * A key verification channel that sends verification events over to_device messages.\n * Generates its own transaction ids.\n */\nexport class ToDeviceChannel {\n // userId and devices of user we're about to verify\n constructor(client, userId, devices, transactionId = null, deviceId = null) {\n this._client = client;\n this.userId = userId;\n this._devices = devices;\n this.transactionId = transactionId;\n this._deviceId = deviceId;\n }\n\n isToDevices(devices) {\n if (devices.length === this._devices.length) {\n for (const device of devices) {\n const d = this._devices.find(d => d.deviceId === device.deviceId);\n if (!d) {\n return false;\n }\n }\n return true;\n } else {\n return false;\n }\n }\n\n get deviceId() {\n return this._deviceId;\n }\n\n static getEventType(event) {\n return event.getType();\n }\n\n /**\n * Extract the transaction id used by a given key verification event, if any\n * @param {MatrixEvent} event the event\n * @returns {string} the transaction id\n */\n static getTransactionId(event) {\n const content = event.getContent();\n return content && content.transaction_id;\n }\n\n /**\n * Checks whether the given event type should be allowed to initiate a new VerificationRequest over this channel\n * @param {string} type the event type to check\n * @returns {bool} boolean flag\n */\n static canCreateRequest(type) {\n return type === REQUEST_TYPE || type === START_TYPE;\n }\n\n /**\n * Checks whether this event is a well-formed key verification event.\n * This only does checks that don't rely on the current state of a potentially already channel\n * so we can prevent channels being created by invalid events.\n * `handleEvent` can do more checks and choose to ignore invalid events.\n * @param {MatrixEvent} event the event to validate\n * @param {MatrixClient} client the client to get the current user and device id from\n * @returns {bool} whether the event is valid and should be passed to handleEvent\n */\n static validateEvent(event, client) {\n if (event.isCancelled()) {\n logger.warn(\"Ignoring flagged verification request from \"\n + event.getSender());\n return false;\n }\n const content = event.getContent();\n if (!content) {\n logger.warn(\"ToDeviceChannel.validateEvent: invalid: no content\");\n return false;\n }\n\n if (!content.transaction_id) {\n logger.warn(\"ToDeviceChannel.validateEvent: invalid: no transaction_id\");\n return false;\n }\n\n const type = event.getType();\n\n if (type === REQUEST_TYPE) {\n if (!Number.isFinite(content.timestamp)) {\n logger.warn(\"ToDeviceChannel.validateEvent: invalid: no timestamp\");\n return false;\n }\n if (event.getSender() === client.getUserId() &&\n content.from_device == client.getDeviceId()\n ) {\n // ignore requests from ourselves, because it doesn't make sense for a\n // device to verify itself\n logger.warn(\"ToDeviceChannel.validateEvent: invalid: from own device\");\n return false;\n }\n }\n\n return VerificationRequest.validateEvent(type, event, client);\n }\n\n /**\n * @param {MatrixEvent} event the event to get the timestamp of\n * @return {number} the timestamp when the event was sent\n */\n getTimestamp(event) {\n const content = event.getContent();\n return content && content.timestamp;\n }\n\n /**\n * Changes the state ofLine truncated
|
||||
"/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { randomString } from '../../../randomstring';\nimport { logger } from '../../../logger';\nimport {\n CANCEL_TYPE,\n PHASE_STARTED,\n PHASE_READY,\n REQUEST_TYPE,\n READY_TYPE,\n START_TYPE,\n VerificationRequest,\n} from \"./VerificationRequest\";\nimport { errorFromEvent, newUnexpectedMessageError } from \"../Error\";\nimport { MatrixEvent } from \"../../../models/event\";\n\n/**\n * A key verification channel that sends verification events over to_device messages.\n * Generates its own transaction ids.\n */\nexport class ToDeviceChannel {\n // userId and devices of user we're about to verify\n constructor(client, userId, devices, transactionId = null, deviceId = null) {\n this._client = client;\n this.userId = userId;\n this._devices = devices;\n this.transactionId = transactionId;\n this._deviceId = deviceId;\n }\n\n isToDevices(devices) {\n if (devices.length === this._devices.length) {\n for (const device of devices) {\n const d = this._devices.find(d => d.deviceId === device.deviceId);\n if (!d) {\n return false;\n }\n }\n return true;\n } else {\n return false;\n }\n }\n\n get deviceId() {\n return this._deviceId;\n }\n\n static getEventType(event) {\n return event.getType();\n }\n\n /**\n * Extract the transaction id used by a given key verification event, if any\n * @param {MatrixEvent} event the event\n * @returns {string} the transaction id\n */\n static getTransactionId(event) {\n const content = event.getContent();\n return content && content.transaction_id;\n }\n\n /**\n * Checks whether the given event type should be allowed to initiate a new VerificationRequest over this channel\n * @param {string} type the event type to check\n * @returns {bool} boolean flag\n */\n static canCreateRequest(type) {\n return type === REQUEST_TYPE || type === START_TYPE;\n }\n\n /**\n * Checks whether this event is a well-formed key verification event.\n * This only does checks that don't rely on the current state of a potentially already channel\n * so we can prevent channels being created by invalid events.\n * `handleEvent` can do more checks and choose to ignore invalid events.\n * @param {MatrixEvent} event the event to validate\n * @param {MatrixClient} client the client to get the current user and device id from\n * @returns {bool} whether the event is valid and should be passed to handleEvent\n */\n static validateEvent(event, client) {\n if (event.isCancelled()) {\n logger.warn(\"Ignoring flagged verification request from \"\n + event.getSender());\n return false;\n }\n const content = event.getContent();\n if (!content) {\n logger.warn(\"ToDeviceChannel.validateEvent: invalid: no content\");\n return false;\n }\n\n if (!content.transaction_id) {\n logger.warn(\"ToDeviceChannel.validateEvent: invalid: no transaction_id\");\n return false;\n }\n\n const type = event.getType();\n\n if (type === REQUEST_TYPE) {\n if (!Number.isFinite(content.timestamp)) {\n logger.warn(\"ToDeviceChannel.validateEvent: invalid: no timestamp\");\n return false;\n }\n if (event.getSender() === client.getUserId() &&\n content.from_device == client.getDeviceId()\n ) {\n // ignore requests from ourselves, because it doesn't make sense for a\n // device to verify itself\n logger.warn(\"ToDeviceChannel.validateEvent: invalid: from own device\");\n return false;\n }\n }\n\n return VerificationRequest.validateEvent(type, event, client);\n }\n\n /**\n * @param {MatrixEvent} event the event to get the timestamp of\n * @return {number} the timestamp when the event was sent\n */\n getTimestamp(event) {\n const content = event.getContent();\n return content && content.timestamp;\n }\n\n /**\n * Changes the state ofLine truncated
|
||||
"/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from '../../../logger';\nimport { EventEmitter } from 'events';\nimport {\n errorFactory,\n errorFromEvent,\n newUnexpectedMessageError,\n newUnknownMethodError,\n} from \"../Error\";\nimport { QRCodeData, SCAN_QR_CODE_METHOD } from \"../QRCode\";\n\n// How long after the event's timestamp that the request times out\nconst TIMEOUT_FROM_EVENT_TS = 10 * 60 * 1000; // 10 minutes\n\n// How long after we receive the event that the request times out\nconst TIMEOUT_FROM_EVENT_RECEIPT = 2 * 60 * 1000; // 2 minutes\n\n// to avoid almost expired verification notifications\n// from showing a notification and almost immediately\n// disappearing, also ignore verification requests that\n// are this amount of time away from expiring.\nconst VERIFICATION_REQUEST_MARGIN = 3 * 1000; // 3 seconds\n\nexport const EVENT_PREFIX = \"m.key.verification.\";\nexport const REQUEST_TYPE = EVENT_PREFIX + \"request\";\nexport const START_TYPE = EVENT_PREFIX + \"start\";\nexport const CANCEL_TYPE = EVENT_PREFIX + \"cancel\";\nexport const DONE_TYPE = EVENT_PREFIX + \"done\";\nexport const READY_TYPE = EVENT_PREFIX + \"ready\";\n\nexport const PHASE_UNSENT = 1;\nexport const PHASE_REQUESTED = 2;\nexport const PHASE_READY = 3;\nexport const PHASE_STARTED = 4;\nexport const PHASE_CANCELLED = 5;\nexport const PHASE_DONE = 6;\n\n/**\n * State machine for verification requests.\n * Things that differ based on what channel is used to\n * send and receive verification events are put in `InRoomChannel` or `ToDeviceChannel`.\n * @event \"change\" whenever the state of the request object has changed.\n */\nexport class VerificationRequest extends EventEmitter {\n constructor(channel, verificationMethods, client) {\n super();\n this.channel = channel;\n this.channel._request = this;\n this._verificationMethods = verificationMethods;\n this._client = client;\n this._commonMethods = [];\n this._setPhase(PHASE_UNSENT, false);\n this._eventsByUs = new Map();\n this._eventsByThem = new Map();\n this._observeOnly = false;\n this._timeoutTimer = null;\n this._accepting = false;\n this._declining = false;\n this._verifierHasFinished = false;\n this._cancelled = false;\n this._chosenMethod = null;\n // we keep a copy of the QR Code data (including other user master key) around\n // for QR reciprocate verification, to protect against\n // cross-signing identity reset between the .ready and .start event\n // and signing the wrong key after .start\n this._qrCodeData = null;\n\n // The timestamp when we received the request event from the other side\n this._requestReceivedAt = null;\n }\n\n /**\n * Stateless validation logic not specific to the channel.\n * Invoked by the same static method in either channel.\n * @param {string} type the \"symbolic\" event type, as returned by the `getEventType` function on the channel.\n * @param {MatrixEvent} event the event to validate. Don't call getType() on it but use the `type` parameter instead.\n * @param {MatrixClient} client the client to get the current user and device id from\n * @returns {bool} whether the event is valid and should be passed to handleEvent\n */\n static validateEvent(type, event, client) {\n const content = event.getContent();\n\n if (!type || !type.startsWith(EVENT_PREFIX)) {\n return false;\n }\n\n // from here on we're fairly sure that this is supposed to be\n // part of a verification request, so be noisy when rejecting something\n if (!content) {\n logger.log(\"VerificationRequest: validateEvent: no content\");\n return false;\n }\n\n if (type === REQUEST_TYPE || type === READY_TYPE) {\n if (!Array.isArray(content.methods)) {\n logger.log(\"VerificationRequest: validateEvent: \" +\n \"fail because methods\");\n return false;\n }\n }\n\n if (type === REQUEST_TYPE || type === READY_TYPE || type === START_TYPE) {\n if (typeof content.from_device !== \"string\" ||\n content.from_device.length === 0\n ) {\n logger.log(\"VerifLine truncated
|
||||
"// can't just do InvalidStoreError extends Error\n// because of http://babeljs.io/docs/usage/caveats/#classes\nexport function InvalidStoreError(reason, value) {\n const message = `Store is invalid because ${reason}, ` +\n `please stop the client, delete all data and start the client again`;\n const instance = Reflect.construct(Error, [message]);\n Reflect.setPrototypeOf(instance, Reflect.getPrototypeOf(this));\n instance.reason = reason;\n instance.value = value;\n return instance;\n}\n\nInvalidStoreError.TOGGLED_LAZY_LOADING = \"TOGGLED_LAZY_LOADING\";\n\nInvalidStoreError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: Error,\n enumerable: false,\n writable: true,\n configurable: true,\n },\n});\nReflect.setPrototypeOf(InvalidStoreError, Error);\n\nexport function InvalidCryptoStoreError(reason) {\n const message = `Crypto store is invalid because ${reason}, ` +\n `please stop the client, delete all data and start the client again`;\n const instance = Reflect.construct(Error, [message]);\n Reflect.setPrototypeOf(instance, Reflect.getPrototypeOf(this));\n instance.reason = reason;\n instance.name = 'InvalidCryptoStoreError';\n return instance;\n}\n\nInvalidCryptoStoreError.TOO_NEW = \"TOO_NEW\";\n\nInvalidCryptoStoreError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: Error,\n enumerable: false,\n writable: true,\n configurable: true,\n },\n});\nReflect.setPrototypeOf(InvalidCryptoStoreError, Error);\n\nexport class KeySignatureUploadError extends Error {\n constructor(message, value) {\n super(message);\n this.value = value;\n }\n}\n",
|
||||
"/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixClient } from \"./client\";\nimport { IEvent, MatrixEvent } from \"./models/event\";\n\nexport type EventMapper = (obj: Partial<IEvent>) => MatrixEvent;\n\nexport interface MapperOpts {\n preventReEmit?: boolean;\n decrypt?: boolean;\n}\n\nexport function eventMapperFor(client: MatrixClient, options: MapperOpts): EventMapper {\n const preventReEmit = Boolean(options.preventReEmit);\n const decrypt = options.decrypt !== false;\n\n function mapper(plainOldJsObject: Partial<IEvent>) {\n const event = new MatrixEvent(plainOldJsObject);\n if (event.isEncrypted()) {\n if (!preventReEmit) {\n client.reEmitter.reEmit(event, [\n \"Event.decrypted\",\n ]);\n }\n if (decrypt) {\n client.decryptEventIfNeeded(event);\n }\n }\n if (!preventReEmit) {\n client.reEmitter.reEmit(event, [\"Event.replaced\"]);\n }\n return event;\n }\n\n return mapper;\n}\n",
|
||||
@@ -278,42 +279,43 @@
|
||||
"/*\nCopyright 2015 - 2021 Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module filter\n */\n\nimport { FilterComponent, IFilterComponent } from \"./filter-component\";\nimport { MatrixEvent } from \"./models/event\";\n\n/**\n * @param {Object} obj\n * @param {string} keyNesting\n * @param {*} val\n */\nfunction setProp(obj: object, keyNesting: string, val: any) {\n const nestedKeys = keyNesting.split(\".\");\n let currentObj = obj;\n for (let i = 0; i < (nestedKeys.length - 1); i++) {\n if (!currentObj[nestedKeys[i]]) {\n currentObj[nestedKeys[i]] = {};\n }\n currentObj = currentObj[nestedKeys[i]];\n }\n currentObj[nestedKeys[nestedKeys.length - 1]] = val;\n}\n\n/* eslint-disable camelcase */\nexport interface IFilterDefinition {\n event_fields?: string[];\n event_format?: \"client\" | \"federation\";\n presence?: IFilterComponent;\n account_data?: IFilterComponent;\n room?: IRoomFilter;\n}\n\nexport interface IRoomEventFilter extends IFilterComponent {\n lazy_load_members?: boolean;\n include_redundant_members?: boolean;\n}\n\ninterface IStateFilter extends IRoomEventFilter {}\n\ninterface IRoomFilter {\n not_rooms?: string[];\n rooms?: string[];\n ephemeral?: IRoomEventFilter;\n include_leave?: boolean;\n state?: IStateFilter;\n timeline?: IRoomEventFilter;\n account_data?: IRoomEventFilter;\n}\n/* eslint-enable camelcase */\n\n/**\n * Construct a new Filter.\n * @constructor\n * @param {string} userId The user ID for this filter.\n * @param {string=} filterId The filter ID if known.\n * @prop {string} userId The user ID of the filter\n * @prop {?string} filterId The filter ID\n */\nexport class Filter {\n static LAZY_LOADING_MESSAGES_FILTER = {\n lazy_load_members: true,\n };\n\n /**\n * Create a filter from existing data.\n * @static\n * @param {string} userId\n * @param {string} filterId\n * @param {Object} jsonObj\n * @return {Filter}\n */\n public static fromJson(userId: string, filterId: string, jsonObj: IFilterDefinition): Filter {\n const filter = new Filter(userId, filterId);\n filter.setDefinition(jsonObj);\n return filter;\n }\n\n private definition: IFilterDefinition = {};\n private roomFilter: FilterComponent;\n private roomTimelineFilter: FilterComponent;\n\n constructor(public readonly userId: string, public filterId?: string) {}\n\n /**\n * Get the ID of this filter on your homeserver (if known)\n * @return {?string} The filter ID\n */\n getFilterId(): string | null {\n return this.filterId;\n }\n\n /**\n * Get the JSON body of the filter.\n * @return {Object} The filter definition\n */\n getDefinition(): IFilterDefinition {\n return this.definition;\n }\n\n /**\n * Set the JSON body of the filter\n * @param {Object} definition The filter definition\n */\n setDefinition(definition: IFilterDefinition) {\n this.definition = definition;\n\n // This is all ported from synapse's FilterCollection()\n\n // definitions look something like:\n // {\n // \"room\": {\n // \"rooms\": [\"!abcde:example.com\"],\n // \"not_rooms\": [\"!123456:example.com\"],\n // \"state\": {\n // \"types\": [\"m.room.*\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"lazy_load_members\": true,\n // },\n // \"timeline\": {\n // \"limit\": 10,\n // \"types\": [\"m.room.message\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"not_senders\": [\"@spam:example.com\"]\n // \"contains_url\": true\n // },\n // \"ephemeral\": {\n // \"types\": [\"m.receipt\", \"m.typing\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"not_senders\": [\"@spam:example.com\"]\n // }\n // },\n // \"presence\": {\n // \"types\": [\"m.presence\"],\n // \"not_senders\": [\"@alice:example.com\"]\n // },\n // \"event_format\": \"client\",\n // \"event_fields\": [\"type\", \"content\", \"sender\"]\n // }\n\n const roomFilterJson = definition.room;\n\n // consider the top level rooms/not_rooms filterLine truncated
|
||||
"/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MatrixHttpApi} for the public class.\n * @module http-api\n */\n\nimport { parse as parseContentType } from \"content-type\";\nimport * as utils from \"./utils\";\nimport { logger } from './logger';\n\n// we use our own implementation of setTimeout, so that if we get suspended in\n// the middle of a /sync, we cancel the sync as soon as we awake, rather than\n// waiting for the delay to elapse.\nimport * as callbacks from \"./realtime-callbacks\";\n\n/*\nTODO:\n- CS: complete register function (doing stages)\n- Identity server: linkEmail, authEmail, bindEmail, lookup3pid\n*/\n\n/**\n * A constant representing the URI path for release 0 of the Client-Server HTTP API.\n */\nexport const PREFIX_R0 = \"/_matrix/client/r0\";\n\n/**\n * A constant representing the URI path for as-yet unspecified Client-Server HTTP APIs.\n */\nexport const PREFIX_UNSTABLE = \"/_matrix/client/unstable\";\n\n/**\n * URI path for v1 of the the identity API\n * @deprecated Use v2.\n */\nexport const PREFIX_IDENTITY_V1 = \"/_matrix/identity/api/v1\";\n\n/**\n * URI path for the v2 identity API\n */\nexport const PREFIX_IDENTITY_V2 = \"/_matrix/identity/v2\";\n\n/**\n * URI path for the media repo API\n */\nexport const PREFIX_MEDIA_R0 = \"/_matrix/media/r0\";\n\n/**\n * Construct a MatrixHttpApi.\n * @constructor\n * @param {EventEmitter} event_emitter The event emitter to use for emitting events\n * @param {Object} opts The options to use for this HTTP API.\n * @param {string} opts.baseUrl Required. The base client-server URL e.g.\n * 'http://localhost:8008'.\n * @param {Function} opts.request Required. The function to call for HTTP\n * requests. This function must look like function(opts, callback){ ... }.\n * @param {string} opts.prefix Required. The matrix client prefix to use, e.g.\n * '/_matrix/client/r0'. See PREFIX_R0 and PREFIX_UNSTABLE for constants.\n *\n * @param {boolean} opts.onlyData True to return only the 'data' component of the\n * response (e.g. the parsed HTTP body). If false, requests will return an\n * object with the properties <tt>code</tt>, <tt>headers</tt> and <tt>data</tt>.\n *\n * @param {string} opts.accessToken The access_token to send with requests. Can be\n * null to not send an access token.\n * @param {Object=} opts.extraParams Optional. Extra query parameters to send on\n * requests.\n * @param {Number=} opts.localTimeoutMs The default maximum amount of time to wait\n * before timing out the request. If not specified, there is no timeout.\n * @param {boolean} [opts.useAuthorizationHeader = false] Set to true to use\n * Authorization header instead of query param to send the access token to the server.\n */\nexport function MatrixHttpApi(event_emitter, opts) {\n utils.checkObjectHasKeys(opts, [\"baseUrl\", \"request\", \"prefix\"]);\n opts.onlyData = opts.onlyData || false;\n this.event_emitter = event_emitter;\n this.opts = opts;\n this.useAuthorizationHeader = Boolean(opts.useAuthorizationHeader);\n this.uploads = [];\n}\n\nMatrixHttpApi.prototype = {\n /**\n * Sets the baase URL for the identity server\n * @param {string} url The new base url\n */\n setIdBaseUrl: function(url) {\n this.opts.idBaseUrl = url;\n },\n\n /**\n * Get the content repository url with query parameters.\n * @return {Object} An object with a 'base', 'path' and 'params' for base URL,\n * path and query parameters respectively.\n */\n getContentUri: function() {\n const params = {\n access_token: this.opts.accessToken,\n };\n return {\n base: this.opts.baseUrl,\n path: \"/_matrix/media/r0/upload\",\n params: params,\n };\n },\n\n /**\n * Upload content to the homeserver\n *\n * @param {object} file The object to upload. On a browser, something that\n * can be sent to XMLHttpRequest.send (typically a File). Under node.js,\n * a Buffer, String or ReadStream.\n *\n * @param {object} opts options object\n *\n * @param {string=} opts.name Name to give the file on the server. Defaults\n * to <tt>file.name</tt>.\n *\n * @param {boolean=} opts.includeFilename if false will not send the filename,\n * e.g for encrypted file uploads where filename lLine truncated
|
||||
"/*\nCopyright 2019 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Check if an IndexedDB database exists. The only way to do so is to try opening it, so\n * we do that and then delete it did not exist before.\n *\n * @param {Object} indexedDB The `indexedDB` interface\n * @param {string} dbName The database name to test for\n * @returns {boolean} Whether the database exists\n */\nexport function exists(indexedDB: IDBFactory, dbName: string): Promise<boolean> {\n return new Promise<boolean>((resolve, reject) => {\n let exists = true;\n const req = indexedDB.open(dbName);\n req.onupgradeneeded = () => {\n // Since we did not provide an explicit version when opening, this event\n // should only fire if the DB did not exist before at any version.\n exists = false;\n };\n req.onblocked = () => reject(req.error);\n req.onsuccess = () => {\n const db = req.result;\n db.close();\n if (!exists) {\n // The DB did not exist before, but has been created as part of this\n // existence check. Delete it now to restore previous state. Delete can\n // actually take a while to complete in some browsers, so don't wait for\n // it. This won't block future open calls that a store might issue next to\n // properly set up the DB.\n indexedDB.deleteDatabase(dbName);\n }\n resolve(exists);\n };\n req.onerror = ev => reject(req.error);\n });\n}\n",
|
||||
"/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/** @module interactive-auth */\n\nimport * as utils from \"./utils\";\nimport { logger } from './logger';\n\nconst EMAIL_STAGE_TYPE = \"m.login.email.identity\";\nconst MSISDN_STAGE_TYPE = \"m.login.msisdn\";\n\n/**\n * Abstracts the logic used to drive the interactive auth process.\n *\n * <p>Components implementing an interactive auth flow should instantiate one of\n * these, passing in the necessary callbacks to the constructor. They should\n * then call attemptAuth, which will return a promise which will resolve or\n * reject when the interactive-auth process completes.\n *\n * <p>Meanwhile, calls will be made to the startAuthStage and doRequest\n * callbacks, and information gathered from the user can be submitted with\n * submitAuthDict.\n *\n * @constructor\n * @alias module:interactive-auth\n *\n * @param {object} opts options object\n *\n * @param {object} opts.matrixClient A matrix client to use for the auth process\n *\n * @param {object?} opts.authData error response from the last request. If\n * null, a request will be made with no auth before starting.\n *\n * @param {function(object?): Promise} opts.doRequest\n * called with the new auth dict to submit the request. Also passes a\n * second deprecated arg which is a flag set to true if this request\n * is a background request. The busyChanged callback should be used\n * instead of the backfround flag. Should return a promise which resolves\n * to the successful response or rejects with a MatrixError.\n *\n * @param {function(bool): Promise} opts.busyChanged\n * called whenever the interactive auth logic becomes busy submitting\n * information provided by the user or finsihes. After this has been\n * called with true the UI should indicate that a request is in progress\n * until it is called again with false.\n *\n * @param {function(string, object?)} opts.stateUpdated\n * called when the status of the UI auth changes, ie. when the state of\n * an auth stage changes of when the auth flow moves to a new stage.\n * The arguments are: the login type (eg m.login.password); and an object\n * which is either an error or an informational object specific to the\n * login type. If the 'errcode' key is defined, the object is an error,\n * and has keys:\n * errcode: string, the textual error code, eg. M_UNKNOWN\n * error: string, human readable string describing the error\n *\n * The login type specific objects are as follows:\n * m.login.email.identity:\n * * emailSid: string, the sid of the active email auth session\n *\n * @param {object?} opts.inputs Inputs provided by the user and used by different\n * stages of the auto process. The inputs provided will affect what flow is chosen.\n *\n * @param {string?} opts.inputs.emailAddress An email address. If supplied, a flow\n * using email verification will be chosen.\n *\n * @param {string?} opts.inputs.phoneCountry An ISO two letter country code. Gives\n * the country that opts.phoneNumber should be resolved relative to.\n *\n * @param {string?} opts.inputs.phoneNumber A phone number. If supplied, a flow\n * using phone number validation will be chosen.\n *\n * @param {string?} opts.sessionId If resuming an existing interactive auth session,\n * the sessionId of that session.\n *\n * @param {string?} opts.clientSecret If resuming an existing interactive auth session,\n * the client secret for that session\n *\n * @param {string?} opts.emailSid If returning from having completed m.login.email.identity\n * auth, the sid for the email verification session.\n *\n * @param {function?} opts.requestEmailToken A function that takes the email address (string),\n * clientSecret (string), attempt number (int) and sessionId (string) and calls the\n * relevant requestToken function and returns the promise returned by that function.\n * If the resulting promise rejects, the rejection will propagate through to the\n * attemptAuth promise.\n *\n */\nexport function InteractiveAuth(opts) {\n this._matrixClient = opts.matrixClient;\n this._data = opts.authData || {};\n this._requestCallback = opts.doRequest;\n this._busyChangedCallback = opts.busyChanged;\n // startAuthStage included for backwards compaLine truncated
|
||||
"/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/** @module interactive-auth */\n\nimport * as utils from \"./utils\";\nimport { logger } from './logger';\nimport { MatrixClient } from \"./client\";\nimport { defer, IDeferred } from \"./utils\";\nimport { MatrixError } from \"./http-api\";\n\nconst EMAIL_STAGE_TYPE = \"m.login.email.identity\";\nconst MSISDN_STAGE_TYPE = \"m.login.msisdn\";\n\ninterface IFlow {\n stages: AuthType[];\n}\n\nexport interface IInputs {\n emailAddress?: string;\n phoneCountry?: string;\n phoneNumber?: string;\n}\n\nexport interface IStageStatus {\n emailSid?: string;\n errcode?: string;\n error?: string;\n}\n\nexport interface IAuthData {\n session?: string;\n completed?: string[];\n flows?: IFlow[];\n params?: Record<string, Record<string, any>>;\n errcode?: string;\n error?: MatrixError;\n}\n\nexport enum AuthType {\n Password = \"m.login.password\",\n Recaptcha = \"m.login.recaptcha\",\n Terms = \"m.login.terms\",\n Email = \"m.login.email.identity\",\n Msisdn = \"m.login.msisdn\",\n Sso = \"m.login.sso\",\n SsoUnstable = \"org.matrix.login.sso\",\n Dummy = \"m.login.dummy\",\n}\n\nexport interface IAuthDict {\n // [key: string]: any;\n type?: string;\n // session?: string; // TODO\n // TODO: Remove `user` once servers support proper UIA\n // See https://github.com/vector-im/element-web/issues/10312\n user?: string;\n identifier?: any;\n password?: string;\n response?: string;\n // TODO: Remove `threepid_creds` once servers support proper UIA\n // See https://github.com/vector-im/element-web/issues/10312\n // See https://github.com/matrix-org/matrix-doc/issues/2220\n // eslint-disable-next-line camelcase\n threepid_creds?: any;\n threepidCreds?: any;\n}\n\nclass NoAuthFlowFoundError extends Error {\n public name = \"NoAuthFlowFoundError\";\n\n // eslint-disable-next-line @typescript-eslint/naming-convention, camelcase\n constructor(m: string, public readonly required_stages: string[], public readonly flows: IFlow[]) {\n super(m);\n }\n}\n\ninterface IOpts {\n matrixClient: MatrixClient;\n authData?: IAuthData;\n inputs?: IInputs;\n sessionId?: string;\n clientSecret?: string;\n emailSid?: string;\n doRequest(auth: IAuthData, background: boolean): Promise<IAuthData>;\n stateUpdated(nextStage: AuthType, status: IStageStatus): void;\n requestEmailToken(email: string, secret: string, attempt: number, session: string): Promise<{ sid: string }>;\n busyChanged?(busy: boolean): void;\n startAuthStage?(nextStage: string): Promise<void>; // LEGACY\n}\n\n/**\n * Abstracts the logic used to drive the interactive auth process.\n *\n * <p>Components implementing an interactive auth flow should instantiate one of\n * these, passing in the necessary callbacks to the constructor. They should\n * then call attemptAuth, which will return a promise which will resolve or\n * reject when the interactive-auth process completes.\n *\n * <p>Meanwhile, calls will be made to the startAuthStage and doRequest\n * callbacks, and information gathered from the user can be submitted with\n * submitAuthDict.\n *\n * @constructor\n * @alias module:interactive-auth\n *\n * @param {object} opts options object\n *\n * @param {object} opts.matrixClient A matrix client to use for the auth process\n *\n * @param {object?} opts.authData error response from the last request. If\n * null, a request will be made with no auth before starting.\n *\n * @param {function(object?): Promise} opts.doRequest\n * called with the new auth dict to submit the request. Also passes a\n * second deprecated arg which is a flag set to true if this request\n * is a background request. The busyChanged callback should be used\n * instead of the background flag. Should return a promise which resolves\n * to the successful response or rejects with a MatrixError.\n *\n * @param {function(boolean): Promise} opts.busyChanged\n * called whenever the interactive auth logic becomes busy submitting\n * information provided by the user or finishes. After this has been\n * called with true the UI should indicate that a request is in progress\n * until it is called again with false.\n *\n * @param {function(string, object?)} opts.stateUpdatedLine truncated
|
||||
"/*\nCopyright 2018 André Jaenisch\nCopyright 2019, 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module logger\n */\n\nimport log, { Logger } from \"loglevel\";\n\n// This is to demonstrate, that you can use any namespace you want.\n// Namespaces allow you to turn on/off the logging for specific parts of the\n// application.\n// An idea would be to control this via an environment variable (on Node.js).\n// See https://www.npmjs.com/package/debug to see how this could be implemented\n// Part of #332 is introducing a logging library in the first place.\nconst DEFAULT_NAMESPACE = \"matrix\";\n\n// because rageshakes in react-sdk hijack the console log, also at module load time,\n// initializing the logger here races with the initialization of rageshakes.\n// to avoid the issue, we override the methodFactory of loglevel that binds to the\n// console methods at initialization time by a factory that looks up the console methods\n// when logging so we always get the current value of console methods.\nlog.methodFactory = function(methodName, logLevel, loggerName) {\n return function(...args) {\n /* eslint-disable @typescript-eslint/no-invalid-this */\n if (this.prefix) {\n args.unshift(this.prefix);\n }\n /* eslint-enable @typescript-eslint/no-invalid-this */\n const supportedByConsole = methodName === \"error\" ||\n methodName === \"warn\" ||\n methodName === \"trace\" ||\n methodName === \"info\";\n /* eslint-disable no-console */\n if (supportedByConsole) {\n return console[methodName](...args);\n } else {\n return console.log(...args);\n }\n /* eslint-enable no-console */\n };\n};\n\n/**\n * Drop-in replacement for <code>console</code> using {@link https://www.npmjs.com/package/loglevel|loglevel}.\n * Can be tailored down to specific use cases if needed.\n */\nexport const logger: PrefixedLogger = log.getLogger(DEFAULT_NAMESPACE);\nlogger.setLevel(log.levels.DEBUG);\n\nexport interface PrefixedLogger extends Logger {\n withPrefix?: (prefix: string) => PrefixedLogger;\n prefix?: string;\n}\n\nfunction extendLogger(logger: PrefixedLogger) {\n logger.withPrefix = function(prefix: string): PrefixedLogger {\n const existingPrefix = this.prefix || \"\";\n return getPrefixedLogger(existingPrefix + prefix);\n };\n}\n\nextendLogger(logger);\n\nfunction getPrefixedLogger(prefix): PrefixedLogger {\n const prefixLogger: PrefixedLogger = log.getLogger(`${DEFAULT_NAMESPACE}-${prefix}`);\n if (prefixLogger.prefix !== prefix) {\n // Only do this setup work the first time through, as loggers are saved by name.\n extendLogger(prefixLogger);\n prefixLogger.prefix = prefix;\n prefixLogger.setLevel(log.levels.DEBUG);\n }\n return prefixLogger;\n}\n",
|
||||
"/*\nCopyright 2015-2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MemoryCryptoStore } from \"./crypto/store/memory-crypto-store\";\nimport { MemoryStore } from \"./store/memory\";\nimport { MatrixScheduler } from \"./scheduler\";\nimport { MatrixClient } from \"./client\";\nimport { ICreateClientOpts } from \"./client\";\nimport { DeviceTrustLevel } from \"./crypto/CrossSigning\";\nimport { ISecretStorageKeyInfo } from \"./crypto/api\";\n\nexport * from \"./client\";\nexport * from \"./http-api\";\nexport * from \"./autodiscovery\";\nexport * from \"./sync-accumulator\";\nexport * from \"./errors\";\nexport * from \"./models/event\";\nexport * from \"./models/room\";\nexport * from \"./models/group\";\nexport * from \"./models/event-timeline\";\nexport * from \"./models/event-timeline-set\";\nexport * from \"./models/room-member\";\nexport * from \"./models/room-state\";\nexport * from \"./models/user\";\nexport * from \"./scheduler\";\nexport * from \"./filter\";\nexport * from \"./timeline-window\";\nexport * from \"./interactive-auth\";\nexport * from \"./service-types\";\nexport * from \"./store/memory\";\nexport * from \"./store/indexeddb\";\nexport * from \"./store/session/webstorage\";\nexport * from \"./crypto/store/memory-crypto-store\";\nexport * from \"./crypto/store/indexeddb-crypto-store\";\nexport * from \"./content-repo\";\nexport * as ContentHelpers from \"./content-helpers\";\nexport {\n createNewMatrixCall,\n setAudioInput as setMatrixCallAudioInput,\n setVideoInput as setMatrixCallVideoInput,\n} from \"./webrtc/call\";\n\n// expose the underlying request object so different environments can use\n// different request libs (e.g. request or browser-request)\nlet requestInstance;\n\n/**\n * The function used to perform HTTP requests. Only use this if you want to\n * use a different HTTP library, e.g. Angular's <code>$http</code>. This should\n * be set prior to calling {@link createClient}.\n * @param {requestFunction} r The request function to use.\n */\nexport function request(r) {\n requestInstance = r;\n}\n\n/**\n * Return the currently-set request function.\n * @return {requestFunction} The current request function.\n */\nexport function getRequest() {\n return requestInstance;\n}\n\n/**\n * Apply wrapping code around the request function. The wrapper function is\n * installed as the new request handler, and when invoked it is passed the\n * previous value, along with the options and callback arguments.\n * @param {requestWrapperFunction} wrapper The wrapping function.\n */\nexport function wrapRequest(wrapper) {\n const origRequest = requestInstance;\n requestInstance = function(options, callback) {\n return wrapper(origRequest, options, callback);\n };\n}\n\nlet cryptoStoreFactory = () => new MemoryCryptoStore;\n\n/**\n * Configure a different factory to be used for creating crypto stores\n *\n * @param {Function} fac a function which will return a new\n * {@link module:crypto.store.base~CryptoStore}.\n */\nexport function setCryptoStoreFactory(fac) {\n cryptoStoreFactory = fac;\n}\n\nexport interface ICryptoCallbacks {\n getCrossSigningKey?: (keyType: string, pubKey: string) => Promise<Uint8Array>;\n saveCrossSigningKeys?: (keys: Record<string, Uint8Array>) => void;\n shouldUpgradeDeviceVerifications?: (\n users: Record<string, any>\n ) => Promise<string[]>;\n getSecretStorageKey?: (\n keys: {keys: Record<string, ISecretStorageKeyInfo>}, name: string\n ) => Promise<[string, Uint8Array] | null>;\n cacheSecretStorageKey?: (\n keyId: string, keyInfo: ISecretStorageKeyInfo, key: Uint8Array\n ) => void;\n onSecretRequested?: (\n userId: string, deviceId: string,\n requestId: string, secretName: string, deviceTrust: DeviceTrustLevel\n ) => Promise<string>;\n getDehydrationKey?: (\n keyInfo: ISecretStorageKeyInfo,\n checkFunc: (Uint8Array) => void,\n ) => Promise<Uint8Array>;\n getBackupKey?: () => Promise<Uint8Array>;\n}\n\n/**\n * Construct a Matrix Client. Similar to {@link module:client.MatrixClient}\n * except that the 'request', 'store' and 'scheduler' dependencies are satisfied.\n * @param {(Object|string)} opts The configuration options for this client. If\n * this is a string, it is assumed to be the base URL. These configuration\n * options will be passed directly to {@link module:client.MatrixClient}.\n * @param {Line truncated
|
||||
"/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixClient } from \"../client\";\nimport { IEncryptedFile, UNSTABLE_MSC3089_BRANCH } from \"../@types/event\";\nimport { MatrixEvent } from \"./event\";\n\n/**\n * Represents a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) branch - a reference\n * to a file (leaf) in the tree. Note that this is UNSTABLE and subject to breaking changes\n * without notice.\n */\nexport class MSC3089Branch {\n public constructor(private client: MatrixClient, public readonly indexEvent: MatrixEvent) {\n // Nothing to do\n }\n\n /**\n * The file ID.\n */\n public get id(): string {\n return this.indexEvent.getStateKey();\n }\n\n /**\n * Whether this branch is active/valid.\n */\n public get isActive(): boolean {\n return this.indexEvent.getContent()[\"active\"] === true;\n }\n\n private get roomId(): string {\n return this.indexEvent.getRoomId();\n }\n\n /**\n * Deletes the file from the tree.\n * @returns {Promise<void>} Resolves when complete.\n */\n public async delete(): Promise<void> {\n await this.client.sendStateEvent(this.roomId, UNSTABLE_MSC3089_BRANCH.name, {}, this.id);\n await this.client.redactEvent(this.roomId, this.id);\n\n // TODO: Delete edit history as well\n }\n\n /**\n * Gets the name for this file.\n * @returns {string} The name, or \"Unnamed File\" if unknown.\n */\n public getName(): string {\n return this.indexEvent.getContent()['name'] || \"Unnamed File\";\n }\n\n /**\n * Sets the name for this file.\n * @param {string} name The new name for this file.\n * @returns {Promise<void>} Resolves when complete.\n */\n public async setName(name: string): Promise<void> {\n await this.client.sendStateEvent(this.roomId, UNSTABLE_MSC3089_BRANCH.name, {\n ...this.indexEvent.getContent(),\n name: name,\n }, this.id);\n }\n\n /**\n * Gets information about the file needed to download it.\n * @returns {Promise<{info: IEncryptedFile, httpUrl: string}>} Information about the file.\n */\n public async getFileInfo(): Promise<{ info: IEncryptedFile, httpUrl: string }> {\n const event = await this.getFileEvent();\n\n const file = event.getContent()['file'];\n const httpUrl = this.client.mxcUrlToHttp(file['url']);\n\n return { info: file, httpUrl: httpUrl };\n }\n\n /**\n * Gets the event the file points to.\n * @returns {Promise<MatrixEvent>} Resolves to the file's event.\n */\n public async getFileEvent(): Promise<MatrixEvent> {\n const room = this.client.getRoom(this.roomId);\n if (!room) throw new Error(\"Unknown room\");\n\n const timeline = await this.client.getEventTimeline(room.getUnfilteredTimelineSet(), this.id);\n if (!timeline) throw new Error(\"Failed to get timeline for room event\");\n\n const event = timeline.getEvents().find(e => e.getId() === this.id);\n if (!event) throw new Error(\"Failed to find event\");\n\n // Sometimes the event context doesn't decrypt for us, so do that.\n await this.client.decryptEventIfNeeded(event, { emit: false, isRetry: false });\n\n return event;\n }\n}\n",
|
||||
"/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixClient } from \"../client\";\nimport { EventType, IEncryptedFile, MsgType, UNSTABLE_MSC3089_BRANCH, UNSTABLE_MSC3089_LEAF } from \"../@types/event\";\nimport { Room } from \"./room\";\nimport { logger } from \"../logger\";\nimport { MatrixEvent } from \"./event\";\nimport {\n averageBetweenStrings,\n DEFAULT_ALPHABET,\n lexicographicCompare,\n nextString,\n prevString,\n simpleRetryOperation,\n} from \"../utils\";\nimport { MSC3089Branch } from \"./MSC3089Branch\";\nimport promiseRetry from \"p-retry\";\nimport { isRoomSharedHistory } from \"../crypto/algorithms/megolm\";\n\n/**\n * The recommended defaults for a tree space's power levels. Note that this\n * is UNSTABLE and subject to breaking changes without notice.\n */\nexport const DEFAULT_TREE_POWER_LEVELS_TEMPLATE = {\n // Owner\n invite: 100,\n kick: 100,\n ban: 100,\n\n // Editor\n redact: 50,\n state_default: 50,\n events_default: 50,\n\n // Viewer\n users_default: 0,\n\n // Mixed\n events: {\n [EventType.RoomPowerLevels]: 100,\n [EventType.RoomHistoryVisibility]: 100,\n [EventType.RoomTombstone]: 100,\n [EventType.RoomEncryption]: 100,\n [EventType.RoomName]: 50,\n [EventType.RoomMessage]: 50,\n [EventType.RoomMessageEncrypted]: 50,\n [EventType.Sticker]: 50,\n },\n\n users: {}, // defined by calling code\n};\n\n/**\n * Ease-of-use representation for power levels represented as simple roles.\n * Note that this is UNSTABLE and subject to breaking changes without notice.\n */\nexport enum TreePermissions {\n Viewer = \"viewer\", // Default\n Editor = \"editor\", // \"Moderator\" or ~PL50\n Owner = \"owner\", // \"Admin\" or PL100\n}\n\n/**\n * Represents a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089)\n * file tree Space. Note that this is UNSTABLE and subject to breaking changes\n * without notice.\n */\nexport class MSC3089TreeSpace {\n public readonly room: Room;\n\n public constructor(private client: MatrixClient, public readonly roomId: string) {\n this.room = this.client.getRoom(this.roomId);\n\n if (!this.room) throw new Error(\"Unknown room\");\n }\n\n /**\n * Syntactic sugar for room ID of the Space.\n */\n public get id(): string {\n return this.roomId;\n }\n\n /**\n * Whether or not this is a top level space.\n */\n public get isTopLevel(): boolean {\n // XXX: This is absolutely not how you find out if the space is top level\n // but is safe for a managed usecase like we offer in the SDK.\n const parentEvents = this.room.currentState.getStateEvents(EventType.SpaceParent);\n if (!parentEvents?.length) return true;\n return parentEvents.every(e => !e.getContent()?.['via']);\n }\n\n /**\n * Sets the name of the tree space.\n * @param {string} name The new name for the space.\n * @returns {Promise<void>} Resolves when complete.\n */\n public async setName(name: string): Promise<void> {\n await this.client.sendStateEvent(this.roomId, EventType.RoomName, { name }, \"\");\n }\n\n /**\n * Invites a user to the tree space. They will be given the default Viewer\n * permission level unless specified elsewhere.\n * @param {string} userId The user ID to invite.\n * @param {boolean} andSubspaces True (default) to invite the user to all\n * directories/subspaces too, recursively.\n * @param {boolean} shareHistoryKeys True (default) to share encryption keys\n * with the invited user. This will allow them to decrypt the events (files)\n * in the tree. Keys will not be shared if the room is lacking appropriate\n * history visibility (by default, history visibility is \"shared\" in trees,\n * which is an appropriate visibility for these purposes).\n * @returns {Promise<void>} Resolves when complete.\n */\n public async invite(userId: string, andSubspaces = true, shareHistoryKeys = true): Promise<void> {\n const promises: Promise<void>[] = [this.retryInvite(userId)];\n if (andSubspaces) {\n promises.push(...this.getDirectories().map(d => d.invite(userId, andSubspaces, shareHistoryKeys)));\n }\n return Promise.all(promises).then(() => {\n // Note: key sharing is default on because Line truncated
|
||||
"/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixClient } from \"../client\";\nimport { EventType, IEncryptedFile, MsgType, UNSTABLE_MSC3089_BRANCH, UNSTABLE_MSC3089_LEAF } from \"../@types/event\";\nimport { Room } from \"./room\";\nimport { logger } from \"../logger\";\nimport { IContent, MatrixEvent } from \"./event\";\nimport {\n averageBetweenStrings,\n DEFAULT_ALPHABET,\n lexicographicCompare,\n nextString,\n prevString,\n simpleRetryOperation,\n} from \"../utils\";\nimport { MSC3089Branch } from \"./MSC3089Branch\";\nimport promiseRetry from \"p-retry\";\nimport { isRoomSharedHistory } from \"../crypto/algorithms/megolm\";\n\n/**\n * The recommended defaults for a tree space's power levels. Note that this\n * is UNSTABLE and subject to breaking changes without notice.\n */\nexport const DEFAULT_TREE_POWER_LEVELS_TEMPLATE = {\n // Owner\n invite: 100,\n kick: 100,\n ban: 100,\n\n // Editor\n redact: 50,\n state_default: 50,\n events_default: 50,\n\n // Viewer\n users_default: 0,\n\n // Mixed\n events: {\n [EventType.RoomPowerLevels]: 100,\n [EventType.RoomHistoryVisibility]: 100,\n [EventType.RoomTombstone]: 100,\n [EventType.RoomEncryption]: 100,\n [EventType.RoomName]: 50,\n [EventType.RoomMessage]: 50,\n [EventType.RoomMessageEncrypted]: 50,\n [EventType.Sticker]: 50,\n },\n\n users: {}, // defined by calling code\n};\n\n/**\n * Ease-of-use representation for power levels represented as simple roles.\n * Note that this is UNSTABLE and subject to breaking changes without notice.\n */\nexport enum TreePermissions {\n Viewer = \"viewer\", // Default\n Editor = \"editor\", // \"Moderator\" or ~PL50\n Owner = \"owner\", // \"Admin\" or PL100\n}\n\n/**\n * Represents a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089)\n * file tree Space. Note that this is UNSTABLE and subject to breaking changes\n * without notice.\n */\nexport class MSC3089TreeSpace {\n public readonly room: Room;\n\n public constructor(private client: MatrixClient, public readonly roomId: string) {\n this.room = this.client.getRoom(this.roomId);\n\n if (!this.room) throw new Error(\"Unknown room\");\n }\n\n /**\n * Syntactic sugar for room ID of the Space.\n */\n public get id(): string {\n return this.roomId;\n }\n\n /**\n * Whether or not this is a top level space.\n */\n public get isTopLevel(): boolean {\n // XXX: This is absolutely not how you find out if the space is top level\n // but is safe for a managed usecase like we offer in the SDK.\n const parentEvents = this.room.currentState.getStateEvents(EventType.SpaceParent);\n if (!parentEvents?.length) return true;\n return parentEvents.every(e => !e.getContent()?.['via']);\n }\n\n /**\n * Sets the name of the tree space.\n * @param {string} name The new name for the space.\n * @returns {Promise<void>} Resolves when complete.\n */\n public async setName(name: string): Promise<void> {\n await this.client.sendStateEvent(this.roomId, EventType.RoomName, { name }, \"\");\n }\n\n /**\n * Invites a user to the tree space. They will be given the default Viewer\n * permission level unless specified elsewhere.\n * @param {string} userId The user ID to invite.\n * @param {boolean} andSubspaces True (default) to invite the user to all\n * directories/subspaces too, recursively.\n * @param {boolean} shareHistoryKeys True (default) to share encryption keys\n * with the invited user. This will allow them to decrypt the events (files)\n * in the tree. Keys will not be shared if the room is lacking appropriate\n * history visibility (by default, history visibility is \"shared\" in trees,\n * which is an appropriate visibility for these purposes).\n * @returns {Promise<void>} Resolves when complete.\n */\n public async invite(userId: string, andSubspaces = true, shareHistoryKeys = true): Promise<void> {\n const promises: Promise<void>[] = [this.retryInvite(userId)];\n if (andSubspaces) {\n promises.push(...this.getDirectories().map(d => d.invite(userId, andSubspaces, shareHistoryKeys)));\n }\n return Promise.all(promises).then(() => {\n // Note: key sharing is default oLine truncated
|
||||
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixEvent } from \"./event\";\nimport { Direction } from \"./event-timeline\";\n\n/**\n * @module models/event-context\n */\nexport class EventContext {\n private timeline: MatrixEvent[];\n private ourEventIndex = 0;\n private paginateTokens: Record<Direction, string | null> = {\n [Direction.Backward]: null,\n [Direction.Forward]: null,\n };\n\n /**\n * Construct a new EventContext\n *\n * An eventcontext is used for circumstances such as search results, when we\n * have a particular event of interest, and a bunch of events before and after\n * it.\n *\n * It also stores pagination tokens for going backwards and forwards in the\n * timeline.\n *\n * @param {MatrixEvent} ourEvent the event at the centre of this context\n *\n * @constructor\n */\n constructor(ourEvent: MatrixEvent) {\n this.timeline = [ourEvent];\n }\n\n /**\n * Get the main event of interest\n *\n * This is a convenience function for getTimeline()[getOurEventIndex()].\n *\n * @return {MatrixEvent} The event at the centre of this context.\n */\n public getEvent(): MatrixEvent {\n return this.timeline[this.ourEventIndex];\n }\n\n /**\n * Get the list of events in this context\n *\n * @return {Array} An array of MatrixEvents\n */\n public getTimeline(): MatrixEvent[] {\n return this.timeline;\n }\n\n /**\n * Get the index in the timeline of our event\n *\n * @return {Number}\n */\n public getOurEventIndex(): number {\n return this.ourEventIndex;\n }\n\n /**\n * Get a pagination token.\n *\n * @param {boolean} backwards true to get the pagination token for going\n * backwards in time\n * @return {string}\n */\n public getPaginateToken(backwards = false): string {\n return this.paginateTokens[backwards ? Direction.Backward : Direction.Forward];\n }\n\n /**\n * Set a pagination token.\n *\n * Generally this will be used only by the matrix js sdk.\n *\n * @param {string} token pagination token\n * @param {boolean} backwards true to set the pagination token for going\n * backwards in time\n */\n public setPaginateToken(token: string, backwards = false): void {\n this.paginateTokens[backwards ? Direction.Backward : Direction.Forward] = token;\n }\n\n /**\n * Add more events to the timeline\n *\n * @param {Array} events new events, in timeline order\n * @param {boolean} atStart true to insert new events at the start\n */\n public addEvents(events: MatrixEvent[], atStart = false): void {\n // TODO: should we share logic with Room.addEventsToTimeline?\n // Should Room even use EventContext?\n\n if (atStart) {\n this.timeline = events.concat(this.timeline);\n this.ourEventIndex += events.length;\n } else {\n this.timeline = this.timeline.concat(events);\n }\n }\n}\n",
|
||||
"/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/event-timeline-set\n */\n\nimport { EventEmitter } from \"events\";\n\nimport { EventTimeline } from \"./event-timeline\";\nimport { EventStatus, MatrixEvent } from \"./event\";\nimport { logger } from '../logger';\nimport { Relations } from './relations';\nimport { Room } from \"./room\";\nimport { Filter } from \"../filter\";\nimport { EventType, RelationType } from \"../@types/event\";\n\n// var DEBUG = false;\nconst DEBUG = true;\n\nlet debuglog;\nif (DEBUG) {\n // using bind means that we get to keep useful line numbers in the console\n debuglog = logger.log.bind(logger);\n} else {\n debuglog = function() {};\n}\n\ninterface IOpts {\n timelineSupport?: boolean;\n filter?: Filter;\n unstableClientRelationAggregation?: boolean;\n}\n\nexport class EventTimelineSet extends EventEmitter {\n private readonly timelineSupport: boolean;\n private unstableClientRelationAggregation: boolean;\n private liveTimeline: EventTimeline;\n private timelines: EventTimeline[];\n private _eventIdToTimeline: Record<string, EventTimeline>;\n private filter?: Filter;\n private relations: Record<string, Record<string, Record<RelationType, Relations>>>;\n\n /**\n * Construct a set of EventTimeline objects, typically on behalf of a given\n * room. A room may have multiple EventTimelineSets for different levels\n * of filtering. The global notification list is also an EventTimelineSet, but\n * lacks a room.\n *\n * <p>This is an ordered sequence of timelines, which may or may not\n * be continuous. Each timeline lists a series of events, as well as tracking\n * the room state at the start and the end of the timeline (if appropriate).\n * It also tracks forward and backward pagination tokens, as well as containing\n * links to the next timeline in the sequence.\n *\n * <p>There is one special timeline - the 'live' timeline, which represents the\n * timeline to which events are being added in real-time as they are received\n * from the /sync API. Note that you should not retain references to this\n * timeline - even if it is the current timeline right now, it may not remain\n * so if the server gives us a timeline gap in /sync.\n *\n * <p>In order that we can find events from their ids later, we also maintain a\n * map from event_id to timeline and index.\n *\n * @constructor\n * @param {?Room} room\n * Room for this timelineSet. May be null for non-room cases, such as the\n * notification timeline.\n * @param {Object} opts Options inherited from Room.\n *\n * @param {boolean} [opts.timelineSupport = false]\n * Set to true to enable improved timeline support.\n * @param {Object} [opts.filter = null]\n * The filter object, if any, for this timelineSet.\n * @param {boolean} [opts.unstableClientRelationAggregation = false]\n * Optional. Set to true to enable client-side aggregation of event relations\n * via `getRelationsForEvent`.\n * This feature is currently unstable and the API may change without notice.\n */\n constructor(public readonly room: Room, opts: IOpts) {\n super();\n\n this.timelineSupport = Boolean(opts.timelineSupport);\n this.liveTimeline = new EventTimeline(this);\n this.unstableClientRelationAggregation = !!opts.unstableClientRelationAggregation;\n\n // just a list - *not* ordered.\n this.timelines = [this.liveTimeline];\n this._eventIdToTimeline = {};\n\n this.filter = opts.filter;\n\n if (this.unstableClientRelationAggregation) {\n // A tree of objects to access a set of relations for an event, as in:\n // this.relations[relatesToEventId][relationType][relationEventType]\n this.relations = {};\n }\n }\n\n /**\n * Get all the timelines in this set\n * @return {module:models/event-timeline~EventTimeline[]} the timelines in this set\n */\n public getTimelines(): EventTimeline[] {\n return this.timelines;\n }\n\n /**\n * Get the filter object this timeline set is filtered on, if any\n * @return {?Filter} the optional filter for this timelineSet\n */\n public getFilter(): Filter | undefined {\n return this.filter;\n }\n\n /**\n * Set the filter oLine truncated
|
||||
"/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/event-timeline\n */\n\nimport { RoomState } from \"./room-state\";\nimport { EventTimelineSet } from \"./event-timeline-set\";\nimport { MatrixEvent } from \"./event\";\nimport { Filter } from \"../filter\";\nimport { EventType } from \"../@types/event\";\n\nexport enum Direction {\n Backward = \"b\",\n Forward = \"f\",\n}\n\nexport class EventTimeline {\n /**\n * Symbolic constant for methods which take a 'direction' argument:\n * refers to the start of the timeline, or backwards in time.\n */\n static BACKWARDS = Direction.Backward;\n\n /**\n * Symbolic constant for methods which take a 'direction' argument:\n * refers to the end of the timeline, or forwards in time.\n */\n static FORWARDS = Direction.Forward;\n\n /**\n * Static helper method to set sender and target properties\n *\n * @param {MatrixEvent} event the event whose metadata is to be set\n * @param {RoomState} stateContext the room state to be queried\n * @param {boolean} toStartOfTimeline if true the event's forwardLooking flag is set false\n */\n static setEventMetadata(event: MatrixEvent, stateContext: RoomState, toStartOfTimeline: boolean): void {\n // When we try to generate a sentinel member before we have that member\n // in the members object, we still generate a sentinel but it doesn't\n // have a membership event, so test to see if events.member is set. We\n // check this to avoid overriding non-sentinel members by sentinel ones\n // when adding the event to a filtered timeline\n if (!event.sender?.events?.member) {\n event.sender = stateContext.getSentinelMember(event.getSender());\n }\n if (!event.target?.events?.member && event.getType() === EventType.RoomMember) {\n event.target = stateContext.getSentinelMember(event.getStateKey());\n }\n\n if (event.isState()) {\n // room state has no concept of 'old' or 'current', but we want the\n // room state to regress back to previous values if toStartOfTimeline\n // is set, which means inspecting prev_content if it exists. This\n // is done by toggling the forwardLooking flag.\n if (toStartOfTimeline) {\n event.forwardLooking = false;\n }\n }\n }\n\n private readonly roomId: string | null;\n private readonly name: string;\n private events: MatrixEvent[] = [];\n private baseIndex = 0;\n private startState: RoomState;\n private endState: RoomState;\n private prevTimeline?: EventTimeline;\n private nextTimeline?: EventTimeline;\n public paginationRequests: Record<Direction, Promise<boolean>> = {\n [Direction.Backward]: null,\n [Direction.Forward]: null,\n };\n\n /**\n * Construct a new EventTimeline\n *\n * <p>An EventTimeline represents a contiguous sequence of events in a room.\n *\n * <p>As well as keeping track of the events themselves, it stores the state of\n * the room at the beginning and end of the timeline, and pagination tokens for\n * going backwards and forwards in the timeline.\n *\n * <p>In order that clients can meaningfully maintain an index into a timeline,\n * the EventTimeline object tracks a 'baseIndex'. This starts at zero, but is\n * incremented when events are prepended to the timeline. The index of an event\n * relative to baseIndex therefore remains constant.\n *\n * <p>Once a timeline joins up with its neighbour, they are linked together into a\n * doubly-linked list.\n *\n * @param {EventTimelineSet} eventTimelineSet the set of timelines this is part of\n * @constructor\n */\n constructor(private readonly eventTimelineSet: EventTimelineSet) {\n this.roomId = eventTimelineSet.room?.roomId ?? null;\n this.startState = new RoomState(this.roomId);\n this.startState.paginationToken = null;\n this.endState = new RoomState(this.roomId);\n this.endState.paginationToken = null;\n\n this.prevTimeline = null;\n this.nextTimeline = null;\n\n // this is used by client.js\n this.paginationRequests = { 'b': null, 'f': null };\n\n this.name = this.roomId + \":\" + new Date().toISOString();\n }\n\n /**\n Line truncated
|
||||
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MatrixEvent} and {@link RoomEvent} for\n * the public classes.\n * @module models/event\n */\n\nimport { EventEmitter } from 'events';\n\nimport { logger } from '../logger';\nimport { VerificationRequest } from \"../crypto/verification/request/VerificationRequest\";\nimport { EventType, MsgType, RelationType } from \"../@types/event\";\nimport { Crypto } from \"../crypto\";\nimport { deepSortedObjectEntries } from \"../utils\";\nimport { RoomMember } from \"./room-member\";\n\n/**\n * Enum for event statuses.\n * @readonly\n * @enum {string}\n */\nexport enum EventStatus {\n /** The event was not sent and will no longer be retried. */\n NOT_SENT = \"not_sent\",\n\n /** The message is being encrypted */\n ENCRYPTING = \"encrypting\",\n\n /** The event is in the process of being sent. */\n SENDING = \"sending\",\n\n /** The event is in a queue waiting to be sent. */\n QUEUED = \"queued\",\n\n /** The event has been sent to the server, but we have not yet received the echo. */\n SENT = \"sent\",\n\n /** The event was cancelled before it was successfully sent. */\n CANCELLED = \"cancelled\",\n}\n\nconst interns: Record<string, string> = {};\nfunction intern(str: string): string {\n if (!interns[str]) {\n interns[str] = str;\n }\n return interns[str];\n}\n\n/* eslint-disable camelcase */\nexport interface IContent {\n [key: string]: any;\n msgtype?: MsgType | string;\n membership?: string;\n avatar_url?: string;\n displayname?: string;\n \"m.relates_to\"?: IEventRelation;\n}\n\ntype StrippedState = Required<Pick<IEvent, \"content\" | \"state_key\" | \"type\" | \"sender\">>;\n\nexport interface IUnsigned {\n age?: number;\n prev_sender?: string;\n prev_content?: IContent;\n redacted_because?: IEvent;\n transaction_id?: string;\n invite_room_state?: StrippedState[];\n}\n\nexport interface IEvent {\n event_id: string;\n type: string;\n content: IContent;\n sender: string;\n room_id: string;\n origin_server_ts: number;\n txn_id?: string;\n state_key?: string;\n membership?: string;\n unsigned: IUnsigned;\n redacts?: string;\n\n // v1 legacy fields\n user_id?: string;\n prev_content?: IContent;\n age?: number;\n}\n\ninterface IAggregatedRelation {\n origin_server_ts: number;\n event_id?: string;\n sender?: string;\n type?: string;\n count?: number;\n key?: string;\n}\n\ninterface IEventRelation {\n rel_type: RelationType | string;\n event_id: string;\n key?: string;\n}\n\ninterface IDecryptionResult {\n clearEvent: {\n room_id?: string;\n type: string;\n content: IContent;\n unsigned?: IUnsigned;\n };\n forwardingCurve25519KeyChain?: string[];\n senderCurve25519Key?: string;\n claimedEd25519Key?: string;\n untrusted?: boolean;\n}\n/* eslint-enable camelcase */\n\nexport interface IClearEvent {\n type: string;\n content: Omit<IContent, \"membership\" | \"avatar_url\" | \"displayname\" | \"m.relates_to\">;\n unsigned?: IUnsigned;\n}\n\ninterface IKeyRequestRecipient {\n userId: string;\n deviceId: \"*\" | string;\n}\n\nexport interface IDecryptOptions {\n emit?: boolean;\n isRetry?: boolean;\n}\n\nexport class MatrixEvent extends EventEmitter {\n private pushActions: object = null;\n private _replacingEvent: MatrixEvent = null;\n private _localRedactionEvent: MatrixEvent = null;\n private _isCancelled = false;\n private clearEvent?: IClearEvent;\n\n /* curve25519 key which we believe belongs to the sender of the event. See\n * getSenderKey()\n */\n private senderCurve25519Key: string = null;\n\n /* ed25519 key which the sender of this event (for olm) or the creator of\n * the megolm session (for megolm) claims to own. See getClaimedEd25519Key()\n */\n private claimedEd25519Key: string = null;\n\n /* curve25519 keys of devices involved in telling us about the\n * senderCurve25519Key and claimedEd25519Key.\n * See getForwardingCurve25519KeyChain().\n */\n private forwardingCurve25519KeyChain: string[] = [];\n\n /* where the decryption key is untrusted\n */\n private untrusted: boolean = null;\n\n /* if we have a process decrypting this event, a Promise which resolves\n * wheLine truncated
|
||||
"/*\nCopyright 2017 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/group\n */\n\nimport * as utils from \"../utils\";\nimport { EventEmitter } from \"events\";\n\n/**\n * Construct a new Group.\n *\n * @param {string} groupId The ID of this group.\n *\n * @prop {string} groupId The ID of this group.\n * @prop {string} name The human-readable display name for this group.\n * @prop {string} avatarUrl The mxc URL for this group's avatar.\n * @prop {string} myMembership The logged in user's membership of this group\n * @prop {Object} inviter Infomation about the user who invited the logged in user\n * to the group, if myMembership is 'invite'.\n * @prop {string} inviter.userId The user ID of the inviter\n */\nexport function Group(groupId) {\n this.groupId = groupId;\n this.name = null;\n this.avatarUrl = null;\n this.myMembership = null;\n this.inviter = null;\n}\nutils.inherits(Group, EventEmitter);\n\nGroup.prototype.setProfile = function(name, avatarUrl) {\n if (this.name === name && this.avatarUrl === avatarUrl) return;\n\n this.name = name || this.groupId;\n this.avatarUrl = avatarUrl;\n\n this.emit(\"Group.profile\", this);\n};\n\nGroup.prototype.setMyMembership = function(membership) {\n if (this.myMembership === membership) return;\n\n this.myMembership = membership;\n\n this.emit(\"Group.myMembership\", this);\n};\n\n/**\n * Sets the 'inviter' property. This does not emit an event (the inviter\n * will only change when the user is revited / reinvited to a room),\n * so set this before setting myMembership.\n * @param {Object} inviter Infomation about who invited us to the room\n */\nGroup.prototype.setInviter = function(inviter) {\n this.inviter = inviter;\n};\n\n/**\n * Fires whenever a group's profile information is updated.\n * This means the 'name' and 'avatarUrl' properties.\n * @event module:client~MatrixClient#\"Group.profile\"\n * @param {Group} group The group whose profile was updated.\n * @example\n * matrixClient.on(\"Group.profile\", function(group){\n * var name = group.name;\n * });\n */\n\n/**\n * Fires whenever the logged in user's membership status of\n * the group is updated.\n * @event module:client~MatrixClient#\"Group.myMembership\"\n * @param {Group} group The group in which the user's membership changed\n * @example\n * matrixClient.on(\"Group.myMembership\", function(group){\n * var myMembership = group.myMembership;\n * });\n */\n",
|
||||
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MatrixEvent} and {@link RoomEvent} for\n * the public classes.\n * @module models/event\n */\n\nimport { EventEmitter } from 'events';\n\nimport { logger } from '../logger';\nimport { VerificationRequest } from \"../crypto/verification/request/VerificationRequest\";\nimport { EventType, MsgType, RelationType } from \"../@types/event\";\nimport { Crypto } from \"../crypto\";\nimport { deepSortedObjectEntries } from \"../utils\";\nimport { RoomMember } from \"./room-member\";\nimport { Thread } from \"./thread\";\nimport { IActionsObject } from '../pushprocessor';\nimport { ReEmitter } from '../ReEmitter';\n\n/**\n * Enum for event statuses.\n * @readonly\n * @enum {string}\n */\nexport enum EventStatus {\n /** The event was not sent and will no longer be retried. */\n NOT_SENT = \"not_sent\",\n\n /** The message is being encrypted */\n ENCRYPTING = \"encrypting\",\n\n /** The event is in the process of being sent. */\n SENDING = \"sending\",\n\n /** The event is in a queue waiting to be sent. */\n QUEUED = \"queued\",\n\n /** The event has been sent to the server, but we have not yet received the echo. */\n SENT = \"sent\",\n\n /** The event was cancelled before it was successfully sent. */\n CANCELLED = \"cancelled\",\n}\n\nconst interns: Record<string, string> = {};\nfunction intern(str: string): string {\n if (!interns[str]) {\n interns[str] = str;\n }\n return interns[str];\n}\n\n/* eslint-disable camelcase */\nexport interface IContent {\n [key: string]: any;\n msgtype?: MsgType | string;\n membership?: string;\n avatar_url?: string;\n displayname?: string;\n \"m.relates_to\"?: IEventRelation;\n}\n\ntype StrippedState = Required<Pick<IEvent, \"content\" | \"state_key\" | \"type\" | \"sender\">>;\n\nexport interface IUnsigned {\n age?: number;\n prev_sender?: string;\n prev_content?: IContent;\n redacted_because?: IEvent;\n transaction_id?: string;\n invite_room_state?: StrippedState[];\n}\n\nexport interface IEvent {\n event_id: string;\n type: string;\n content: IContent;\n sender: string;\n room_id: string;\n origin_server_ts: number;\n txn_id?: string;\n state_key?: string;\n membership?: string;\n unsigned: IUnsigned;\n redacts?: string;\n\n // v1 legacy fields\n user_id?: string;\n prev_content?: IContent;\n age?: number;\n}\n\ninterface IAggregatedRelation {\n origin_server_ts: number;\n event_id?: string;\n sender?: string;\n type?: string;\n count?: number;\n key?: string;\n}\n\ninterface IEventRelation {\n rel_type: RelationType | string;\n event_id: string;\n key?: string;\n}\n\ninterface IDecryptionResult {\n clearEvent: {\n room_id?: string;\n type: string;\n content: IContent;\n unsigned?: IUnsigned;\n };\n forwardingCurve25519KeyChain?: string[];\n senderCurve25519Key?: string;\n claimedEd25519Key?: string;\n untrusted?: boolean;\n}\n/* eslint-enable camelcase */\n\nexport interface IClearEvent {\n type: string;\n content: Omit<IContent, \"membership\" | \"avatar_url\" | \"displayname\" | \"m.relates_to\">;\n unsigned?: IUnsigned;\n}\n\ninterface IKeyRequestRecipient {\n userId: string;\n deviceId: \"*\" | string;\n}\n\nexport interface IDecryptOptions {\n emit?: boolean;\n isRetry?: boolean;\n}\n\nexport class MatrixEvent extends EventEmitter {\n private pushActions: IActionsObject = null;\n private _replacingEvent: MatrixEvent = null;\n private _localRedactionEvent: MatrixEvent = null;\n private _isCancelled = false;\n private clearEvent?: IClearEvent;\n\n /* curve25519 key which we believe belongs to the sender of the event. See\n * getSenderKey()\n */\n private senderCurve25519Key: string = null;\n\n /* ed25519 key which the sender of this event (for olm) or the creator of\n * the megolm session (for megolm) claims to own. See getClaimedEd25519Key()\n */\n private claimedEd25519Key: string = null;\n\n /* curve25519 keys of devices involved in telling us about the\n * senderCurve25519Key and claimedEd25519Key.\n * See getForwardingCurve25519KeyChain().\n */\n private forwardingCurve25519KeyChain: string[] = [];\n\n /* where the decryption key is untrusteLine truncated
|
||||
"/*\nCopyright 2017 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/group\n * @deprecated groups/communities never made it to the spec and support for them is being discontinued.\n */\n\nimport * as utils from \"../utils\";\nimport { EventEmitter } from \"events\";\n\n/**\n * Construct a new Group.\n *\n * @param {string} groupId The ID of this group.\n *\n * @prop {string} groupId The ID of this group.\n * @prop {string} name The human-readable display name for this group.\n * @prop {string} avatarUrl The mxc URL for this group's avatar.\n * @prop {string} myMembership The logged in user's membership of this group\n * @prop {Object} inviter Infomation about the user who invited the logged in user\n * to the group, if myMembership is 'invite'.\n * @prop {string} inviter.userId The user ID of the inviter\n * @deprecated groups/communities never made it to the spec and support for them is being discontinued.\n */\nexport function Group(groupId) {\n this.groupId = groupId;\n this.name = null;\n this.avatarUrl = null;\n this.myMembership = null;\n this.inviter = null;\n}\nutils.inherits(Group, EventEmitter);\n\nGroup.prototype.setProfile = function(name, avatarUrl) {\n if (this.name === name && this.avatarUrl === avatarUrl) return;\n\n this.name = name || this.groupId;\n this.avatarUrl = avatarUrl;\n\n this.emit(\"Group.profile\", this);\n};\n\nGroup.prototype.setMyMembership = function(membership) {\n if (this.myMembership === membership) return;\n\n this.myMembership = membership;\n\n this.emit(\"Group.myMembership\", this);\n};\n\n/**\n * Sets the 'inviter' property. This does not emit an event (the inviter\n * will only change when the user is revited / reinvited to a room),\n * so set this before setting myMembership.\n * @param {Object} inviter Infomation about who invited us to the room\n */\nGroup.prototype.setInviter = function(inviter) {\n this.inviter = inviter;\n};\n\n/**\n * Fires whenever a group's profile information is updated.\n * This means the 'name' and 'avatarUrl' properties.\n * @event module:client~MatrixClient#\"Group.profile\"\n * @param {Group} group The group whose profile was updated.\n * @deprecated groups/communities never made it to the spec and support for them is being discontinued.\n * @example\n * matrixClient.on(\"Group.profile\", function(group){\n * var name = group.name;\n * });\n */\n\n/**\n * Fires whenever the logged in user's membership status of\n * the group is updated.\n * @event module:client~MatrixClient#\"Group.myMembership\"\n * @param {Group} group The group in which the user's membership changed\n * @deprecated groups/communities never made it to the spec and support for them is being discontinued.\n * @example\n * matrixClient.on(\"Group.myMembership\", function(group){\n * var myMembership = group.myMembership;\n * });\n */\n",
|
||||
"/*\nCopyright 2019, 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventEmitter } from 'events';\n\nimport { EventStatus, MatrixEvent } from './event';\nimport { Room } from './room';\nimport { logger } from '../logger';\nimport { RelationType } from \"../@types/event\";\n\n/**\n * A container for relation events that supports easy access to common ways of\n * aggregating such events. Each instance holds events that of a single relation\n * type and event type. All of the events also relate to the same original event.\n *\n * The typical way to get one of these containers is via\n * EventTimelineSet#getRelationsForEvent.\n */\nexport class Relations extends EventEmitter {\n private relationEventIds = new Set<string>();\n private relations = new Set<MatrixEvent>();\n private annotationsByKey: Record<string, Set<MatrixEvent>> = {};\n private annotationsBySender: Record<string, Set<MatrixEvent>> = {};\n private sortedAnnotationsByKey: [string, Set<MatrixEvent>][] = [];\n private targetEvent: MatrixEvent = null;\n private creationEmitted = false;\n\n /**\n * @param {RelationType} relationType\n * The type of relation involved, such as \"m.annotation\", \"m.reference\",\n * \"m.replace\", etc.\n * @param {String} eventType\n * The relation event's type, such as \"m.reaction\", etc.\n * @param {?Room} room\n * Room for this container. May be null for non-room cases, such as the\n * notification timeline.\n */\n constructor(\n public readonly relationType: RelationType | string,\n public readonly eventType: string,\n private readonly room: Room,\n ) {\n super();\n }\n\n /**\n * Add relation events to this collection.\n *\n * @param {MatrixEvent} event\n * The new relation event to be added.\n */\n public async addEvent(event: MatrixEvent) {\n if (this.relationEventIds.has(event.getId())) {\n return;\n }\n\n const relation = event.getRelation();\n if (!relation) {\n logger.error(\"Event must have relation info\");\n return;\n }\n\n const relationType = relation.rel_type;\n const eventType = event.getType();\n\n if (this.relationType !== relationType || this.eventType !== eventType) {\n logger.error(\"Event relation info doesn't match this container\");\n return;\n }\n\n // If the event is in the process of being sent, listen for cancellation\n // so we can remove the event from the collection.\n if (event.isSending()) {\n event.on(\"Event.status\", this.onEventStatus);\n }\n\n this.relations.add(event);\n this.relationEventIds.add(event.getId());\n\n if (this.relationType === RelationType.Annotation) {\n this.addAnnotationToAggregation(event);\n } else if (this.relationType === RelationType.Replace && this.targetEvent) {\n const lastReplacement = await this.getLastReplacement();\n this.targetEvent.makeReplaced(lastReplacement);\n }\n\n event.on(\"Event.beforeRedaction\", this.onBeforeRedaction);\n\n this.emit(\"Relations.add\", event);\n\n this.maybeEmitCreated();\n }\n\n /**\n * Remove relation event from this collection.\n *\n * @param {MatrixEvent} event\n * The relation event to remove.\n */\n private async removeEvent(event: MatrixEvent) {\n if (!this.relations.has(event)) {\n return;\n }\n\n const relation = event.getRelation();\n if (!relation) {\n logger.error(\"Event must have relation info\");\n return;\n }\n\n const relationType = relation.rel_type;\n const eventType = event.getType();\n\n if (this.relationType !== relationType || this.eventType !== eventType) {\n logger.error(\"Event relation info doesn't match this container\");\n return;\n }\n\n this.relations.delete(event);\n\n if (this.relationType === RelationType.Annotation) {\n this.removeAnnotationFromAggregation(event);\n } else if (this.relationType === RelationType.Replace && this.targetEvent) {\n const lastReplacement = await this.getLastReplacement();\n this.targetEvent.makeReplaced(lastReplacement);\n }\n\n this.emit(\"RelaLine truncated
|
||||
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/room-member\n */\n\nimport { EventEmitter } from \"events\";\n\nimport { getHttpUriForMxc } from \"../content-repo\";\nimport * as utils from \"../utils\";\nimport { User } from \"./user\";\nimport { MatrixEvent } from \"./event\";\nimport { RoomState } from \"./room-state\";\n\nexport class RoomMember extends EventEmitter {\n private _isOutOfBand = false;\n private _modified: number;\n public _requestedProfileInfo: boolean; // used by sync.ts\n\n // XXX these should be read-only\n public typing = false;\n public name: string;\n public rawDisplayName: string;\n public powerLevel = 0;\n public powerLevelNorm = 0;\n public user?: User = null;\n public membership: string = null;\n public disambiguate = false;\n public events: {\n member?: MatrixEvent;\n } = {\n member: null,\n };\n\n /**\n * Construct a new room member.\n *\n * @constructor\n * @alias module:models/room-member\n *\n * @param {string} roomId The room ID of the member.\n * @param {string} userId The user ID of the member.\n * @prop {string} roomId The room ID for this member.\n * @prop {string} userId The user ID of this member.\n * @prop {boolean} typing True if the room member is currently typing.\n * @prop {string} name The human-readable name for this room member. This will be\n * disambiguated with a suffix of \" (@user_id:matrix.org)\" if another member shares the\n * same displayname.\n * @prop {string} rawDisplayName The ambiguous displayname of this room member.\n * @prop {Number} powerLevel The power level for this room member.\n * @prop {Number} powerLevelNorm The normalised power level (0-100) for this\n * room member.\n * @prop {User} user The User object for this room member, if one exists.\n * @prop {string} membership The membership state for this room member e.g. 'join'.\n * @prop {Object} events The events describing this RoomMember.\n * @prop {MatrixEvent} events.member The m.room.member event for this RoomMember.\n * @prop {boolean} disambiguate True if the member's name is disambiguated.\n */\n constructor(public readonly roomId: string, public readonly userId: string) {\n super();\n\n this.name = userId;\n this.rawDisplayName = userId;\n this.updateModifiedTime();\n }\n\n /**\n * Mark the member as coming from a channel that is not sync\n */\n public markOutOfBand(): void {\n this._isOutOfBand = true;\n }\n\n /**\n * @return {boolean} does the member come from a channel that is not sync?\n * This is used to store the member seperately\n * from the sync state so it available across browser sessions.\n */\n public isOutOfBand(): boolean {\n return this._isOutOfBand;\n }\n\n /**\n * Update this room member's membership event. May fire \"RoomMember.name\" if\n * this event updates this member's name.\n * @param {MatrixEvent} event The <code>m.room.member</code> event\n * @param {RoomState} roomState Optional. The room state to take into account\n * when calculating (e.g. for disambiguating users with the same name).\n * @fires module:client~MatrixClient#event:\"RoomMember.name\"\n * @fires module:client~MatrixClient#event:\"RoomMember.membership\"\n */\n public setMembershipEvent(event: MatrixEvent, roomState: RoomState): void {\n const displayName = event.getDirectionalContent().displayname;\n\n if (event.getType() !== \"m.room.member\") {\n return;\n }\n\n this._isOutOfBand = false;\n\n this.events.member = event;\n\n const oldMembership = this.membership;\n this.membership = event.getDirectionalContent().membership;\n\n this.disambiguate = shouldDisambiguate(\n this.userId,\n displayName,\n roomState,\n );\n\n const oldName = this.name;\n this.name = calculateDisplayName(\n this.userId,\n displayName,\n roomState,\n this.disambiguate,\n );\n\n this.rawDisplayName = event.getDirectionalContent().displayname;\n if (!this.rawDisplayName || !utils.removeHiddenChars(this.rawDisplayName)) {\n this.rawDisplayName = this.userId;\n }Line truncated
|
||||
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/room-state\n */\n\nimport { EventEmitter } from \"events\";\n\nimport { RoomMember } from \"./room-member\";\nimport { logger } from '../logger';\nimport * as utils from \"../utils\";\nimport { EventType } from \"../@types/event\";\nimport { MatrixEvent } from \"./event\";\nimport { MatrixClient } from \"../client\";\n\n// possible statuses for out-of-band member loading\nenum OobStatus {\n NotStarted,\n InProgress,\n Finished,\n}\n\nexport class RoomState extends EventEmitter {\n private sentinels: Record<string, RoomMember> = {}; // userId: RoomMember\n // stores fuzzy matches to a list of userIDs (applies utils.removeHiddenChars to keys)\n private displayNameToUserIds: Record<string, string[]> = {};\n private userIdsToDisplayNames: Record<string, string> = {};\n private tokenToInvite: Record<string, MatrixEvent> = {}; // 3pid invite state_key to m.room.member invite\n private joinedMemberCount: number = null; // cache of the number of joined members\n // joined members count from summary api\n // once set, we know the server supports the summary api\n // and we should only trust that\n // we could also only trust that before OOB members\n // are loaded but doesn't seem worth the hassle atm\n private summaryJoinedMemberCount: number = null;\n // same for invited member count\n private invitedMemberCount: number = null;\n private summaryInvitedMemberCount: number = null;\n private modified: number;\n\n // XXX: Should be read-only\n public members: Record<string, RoomMember> = {}; // userId: RoomMember\n public events = new Map<string, Map<string, MatrixEvent>>(); // Map<eventType, Map<stateKey, MatrixEvent>>\n public paginationToken: string = null;\n\n /**\n * Construct room state.\n *\n * Room State represents the state of the room at a given point.\n * It can be mutated by adding state events to it.\n * There are two types of room member associated with a state event:\n * normal member objects (accessed via getMember/getMembers) which mutate\n * with the state to represent the current state of that room/user, eg.\n * the object returned by getMember('@bob:example.com') will mutate to\n * get a different display name if Bob later changes his display name\n * in the room.\n * There are also 'sentinel' members (accessed via getSentinelMember).\n * These also represent the state of room members at the point in time\n * represented by the RoomState object, but unlike objects from getMember,\n * sentinel objects will always represent the room state as at the time\n * getSentinelMember was called, so if Bob subsequently changes his display\n * name, a room member object previously acquired with getSentinelMember\n * will still have his old display name. Calling getSentinelMember again\n * after the display name change will return a new RoomMember object\n * with Bob's new display name.\n *\n * @constructor\n * @param {?string} roomId Optional. The ID of the room which has this state.\n * If none is specified it just tracks paginationTokens, useful for notifTimelineSet\n * @param {?object} oobMemberFlags Optional. The state of loading out of bound members.\n * As the timeline might get reset while they are loading, this state needs to be inherited\n * and shared when the room state is cloned for the new timeline.\n * This should only be passed from clone.\n * @prop {Object.<string, RoomMember>} members The room member dictionary, keyed\n * on the user's ID.\n * @prop {Object.<string, Object.<string, MatrixEvent>>} events The state\n * events dictionary, keyed on the event type and then the state_key value.\n * @prop {string} paginationToken The pagination token for this state.\n */\n constructor(public readonly roomId: string, private oobMemberFlags = { status: OobStatus.NotStarted }) {\n super();\n this.updateModifiedTime();\n }\n\n /**\n * Returns the number of joined members in this room\n * This method caches the result.\n * @return {number} The number of members in this room whose membership is 'join'\n */\n public getJoinedMemberCount(): number {\n if (this.summaryJoinedMemberCount !== null) {\n return this.summaryJoinedMemLine truncated
|
||||
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/room-summary\n */\n\nexport interface IRoomSummary {\n \"m.heroes\": string[];\n \"m.joined_member_count\": number;\n \"m.invited_member_count\": number;\n}\n\ninterface IInfo {\n title: string;\n desc?: string;\n numMembers?: number;\n aliases?: string[];\n timestamp?: number;\n}\n\n/**\n * Construct a new Room Summary. A summary can be used for display on a recent\n * list, without having to load the entire room list into memory.\n * @constructor\n * @param {string} roomId Required. The ID of this room.\n * @param {Object} info Optional. The summary info. Additional keys are supported.\n * @param {string} info.title The title of the room (e.g. <code>m.room.name</code>)\n * @param {string} info.desc The description of the room (e.g.\n * <code>m.room.topic</code>)\n * @param {Number} info.numMembers The number of joined users.\n * @param {string[]} info.aliases The list of aliases for this room.\n * @param {Number} info.timestamp The timestamp for this room.\n */\nexport class RoomSummary {\n constructor(public readonly roomId: string, info?: IInfo) {}\n}\n\n",
|
||||
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/room\n */\n\nimport { EventEmitter } from \"events\";\n\nimport { EventTimelineSet } from \"./event-timeline-set\";\nimport { EventTimeline } from \"./event-timeline\";\nimport { getHttpUriForMxc } from \"../content-repo\";\nimport * as utils from \"../utils\";\nimport { normalize } from \"../utils\";\nimport { EventStatus, IEvent, MatrixEvent } from \"./event\";\nimport { RoomMember } from \"./room-member\";\nimport { IRoomSummary, RoomSummary } from \"./room-summary\";\nimport { logger } from '../logger';\nimport { ReEmitter } from '../ReEmitter';\nimport { EventType, RoomCreateTypeField, RoomType, UNSTABLE_ELEMENT_FUNCTIONAL_USERS } from \"../@types/event\";\nimport { IRoomVersionsCapability, MatrixClient, PendingEventOrdering, RoomVersionStability } from \"../client\";\nimport { ResizeMethod } from \"../@types/partials\";\nimport { Filter } from \"../filter\";\nimport { RoomState } from \"./room-state\";\n\n// These constants are used as sane defaults when the homeserver doesn't support\n// the m.room_versions capability. In practice, KNOWN_SAFE_ROOM_VERSION should be\n// the same as the common default room version whereas SAFE_ROOM_VERSIONS are the\n// room versions which are considered okay for people to run without being asked\n// to upgrade (ie: \"stable\"). Eventually, we should remove these when all homeservers\n// return an m.room_versions capability.\nconst KNOWN_SAFE_ROOM_VERSION = '6';\nconst SAFE_ROOM_VERSIONS = ['1', '2', '3', '4', '5', '6'];\n\nfunction synthesizeReceipt(userId: string, event: MatrixEvent, receiptType: string): MatrixEvent {\n // console.log(\"synthesizing receipt for \"+event.getId());\n // This is really ugly because JS has no way to express an object literal\n // where the name of a key comes from an expression\n const fakeReceipt = {\n content: {},\n type: \"m.receipt\",\n room_id: event.getRoomId(),\n };\n fakeReceipt.content[event.getId()] = {};\n fakeReceipt.content[event.getId()][receiptType] = {};\n fakeReceipt.content[event.getId()][receiptType][userId] = {\n ts: event.getTs(),\n };\n return new MatrixEvent(fakeReceipt);\n}\n\ninterface IOpts {\n storageToken?: string;\n pendingEventOrdering?: PendingEventOrdering;\n timelineSupport?: boolean;\n unstableClientRelationAggregation?: boolean;\n lazyLoadMembers?: boolean;\n}\n\nexport interface IRecommendedVersion {\n version: string;\n needsUpgrade: boolean;\n urgent: boolean;\n}\n\ninterface IReceipt {\n ts: number;\n}\n\ninterface IWrappedReceipt {\n eventId: string;\n data: IReceipt;\n}\n\ninterface ICachedReceipt {\n type: string;\n userId: string;\n data: IReceipt;\n}\n\ntype ReceiptCache = Record<string, ICachedReceipt[]>;\n\ninterface IReceiptContent {\n [eventId: string]: {\n [type: string]: {\n [userId: string]: IReceipt;\n };\n };\n}\n\ntype Receipts = Record<string, Record<string, IWrappedReceipt>>;\n\nexport enum NotificationCountType {\n Highlight = \"highlight\",\n Total = \"total\",\n}\n\nexport class Room extends EventEmitter {\n private readonly reEmitter: ReEmitter;\n private txnToEvent: Record<string, MatrixEvent> = {}; // Pending in-flight requests { string: MatrixEvent }\n // receipts should clobber based on receipt_type and user_id pairs hence\n // the form of this structure. This is sub-optimal for the exposed APIs\n // which pass in an event ID and get back some receipts, so we also store\n // a pre-cached list for this purpose.\n private receipts: Receipts = {}; // { receipt_type: { user_id: IReceipt } }\n private receiptCacheByEventId: ReceiptCache = {}; // { event_id: IReceipt2[] }\n // only receipts that came from the server, not synthesized ones\n private realReceipts: Receipts = {};\n private notificationCounts: Partial<Record<NotificationCountType, number>> = {};\n private readonly timelineSets: EventTimelineSet[];\n // any filtered timeline sets we're maintaining for this room\n private readonly filteredTimelineSets: Record<string, EventTimelineSet> = {}; // filter_id: timelineSet\n private readonly pendingEventList?: MatrixEvent[];\n // read by megolm via getter; boolean value - null indicates \"use global value\"\n private blacklistUnverifiedDevices: boolean = null;\n privLine truncated
|
||||
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/search-result\n */\n\nimport { EventContext } from \"./event-context\";\nimport { EventMapper } from \"../event-mapper\";\nimport { IResultContext, ISearchResult } from \"../@types/search\";\n\nexport class SearchResult {\n /**\n * Create a SearchResponse from the response to /search\n * @static\n * @param {Object} jsonObj\n * @param {function} eventMapper\n * @return {SearchResult}\n */\n\n static fromJson(jsonObj: ISearchResult, eventMapper: EventMapper): SearchResult {\n const jsonContext = jsonObj.context || {} as IResultContext;\n const eventsBefore = jsonContext.events_before || [];\n const eventsAfter = jsonContext.events_after || [];\n\n const context = new EventContext(eventMapper(jsonObj.result));\n\n context.setPaginateToken(jsonContext.start, true);\n context.addEvents(eventsBefore.map(eventMapper), true);\n context.addEvents(eventsAfter.map(eventMapper), false);\n context.setPaginateToken(jsonContext.end, false);\n\n return new SearchResult(jsonObj.rank, context);\n }\n\n /**\n * Construct a new SearchResult\n *\n * @param {number} rank where this SearchResult ranks in the results\n * @param {event-context.EventContext} context the matching event and its\n * context\n *\n * @constructor\n */\n constructor(public readonly rank: number, public readonly context: EventContext) {}\n}\n\n",
|
||||
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/room\n */\n\nimport { EventEmitter } from \"events\";\n\nimport { EventTimelineSet } from \"./event-timeline-set\";\nimport { EventTimeline } from \"./event-timeline\";\nimport { getHttpUriForMxc } from \"../content-repo\";\nimport * as utils from \"../utils\";\nimport { normalize } from \"../utils\";\nimport { EventStatus, IEvent, MatrixEvent } from \"./event\";\nimport { RoomMember } from \"./room-member\";\nimport { IRoomSummary, RoomSummary } from \"./room-summary\";\nimport { logger } from '../logger';\nimport { ReEmitter } from '../ReEmitter';\nimport { EventType, RoomCreateTypeField, RoomType, UNSTABLE_ELEMENT_FUNCTIONAL_USERS } from \"../@types/event\";\nimport { IRoomVersionsCapability, MatrixClient, PendingEventOrdering, RoomVersionStability } from \"../client\";\nimport { ResizeMethod } from \"../@types/partials\";\nimport { Filter } from \"../filter\";\nimport { RoomState } from \"./room-state\";\nimport { Thread } from \"./thread\";\n\n// These constants are used as sane defaults when the homeserver doesn't support\n// the m.room_versions capability. In practice, KNOWN_SAFE_ROOM_VERSION should be\n// the same as the common default room version whereas SAFE_ROOM_VERSIONS are the\n// room versions which are considered okay for people to run without being asked\n// to upgrade (ie: \"stable\"). Eventually, we should remove these when all homeservers\n// return an m.room_versions capability.\nconst KNOWN_SAFE_ROOM_VERSION = '6';\nconst SAFE_ROOM_VERSIONS = ['1', '2', '3', '4', '5', '6'];\n\nfunction synthesizeReceipt(userId: string, event: MatrixEvent, receiptType: string): MatrixEvent {\n // console.log(\"synthesizing receipt for \"+event.getId());\n // This is really ugly because JS has no way to express an object literal\n // where the name of a key comes from an expression\n const fakeReceipt = {\n content: {},\n type: \"m.receipt\",\n room_id: event.getRoomId(),\n };\n fakeReceipt.content[event.getId()] = {};\n fakeReceipt.content[event.getId()][receiptType] = {};\n fakeReceipt.content[event.getId()][receiptType][userId] = {\n ts: event.getTs(),\n };\n return new MatrixEvent(fakeReceipt);\n}\n\ninterface IOpts {\n storageToken?: string;\n pendingEventOrdering?: PendingEventOrdering;\n timelineSupport?: boolean;\n unstableClientRelationAggregation?: boolean;\n lazyLoadMembers?: boolean;\n}\n\nexport interface IRecommendedVersion {\n version: string;\n needsUpgrade: boolean;\n urgent: boolean;\n}\n\ninterface IReceipt {\n ts: number;\n}\n\ninterface IWrappedReceipt {\n eventId: string;\n data: IReceipt;\n}\n\ninterface ICachedReceipt {\n type: string;\n userId: string;\n data: IReceipt;\n}\n\ntype ReceiptCache = Record<string, ICachedReceipt[]>;\n\ninterface IReceiptContent {\n [eventId: string]: {\n [type: string]: {\n [userId: string]: IReceipt;\n };\n };\n}\n\ntype Receipts = Record<string, Record<string, IWrappedReceipt>>;\n\nexport enum NotificationCountType {\n Highlight = \"highlight\",\n Total = \"total\",\n}\n\nexport class Room extends EventEmitter {\n private readonly reEmitter: ReEmitter;\n private txnToEvent: Record<string, MatrixEvent> = {}; // Pending in-flight requests { string: MatrixEvent }\n // receipts should clobber based on receipt_type and user_id pairs hence\n // the form of this structure. This is sub-optimal for the exposed APIs\n // which pass in an event ID and get back some receipts, so we also store\n // a pre-cached list for this purpose.\n private receipts: Receipts = {}; // { receipt_type: { user_id: IReceipt } }\n private receiptCacheByEventId: ReceiptCache = {}; // { event_id: IReceipt2[] }\n // only receipts that came from the server, not synthesized ones\n private realReceipts: Receipts = {};\n private notificationCounts: Partial<Record<NotificationCountType, number>> = {};\n private readonly timelineSets: EventTimelineSet[];\n // any filtered timeline sets we're maintaining for this room\n private readonly filteredTimelineSets: Record<string, EventTimelineSet> = {}; // filter_id: timelineSet\n private readonly pendingEventList?: MatrixEvent[];\n // read by megolm via getter; boolean value - null indicates \"use global value\"\n private blacklistUnveriLine truncated
|
||||
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/search-result\n */\n\nimport { EventContext } from \"./event-context\";\nimport { EventMapper } from \"../event-mapper\";\nimport { IResultContext, ISearchResult } from \"../@types/search\";\n\nexport class SearchResult {\n /**\n * Create a SearchResponse from the response to /search\n * @static\n * @param {Object} jsonObj\n * @param {function} eventMapper\n * @return {SearchResult}\n */\n\n public static fromJson(jsonObj: ISearchResult, eventMapper: EventMapper): SearchResult {\n const jsonContext = jsonObj.context || {} as IResultContext;\n const eventsBefore = jsonContext.events_before || [];\n const eventsAfter = jsonContext.events_after || [];\n\n const context = new EventContext(eventMapper(jsonObj.result));\n\n context.setPaginateToken(jsonContext.start, true);\n context.addEvents(eventsBefore.map(eventMapper), true);\n context.addEvents(eventsAfter.map(eventMapper), false);\n context.setPaginateToken(jsonContext.end, false);\n\n return new SearchResult(jsonObj.rank, context);\n }\n\n /**\n * Construct a new SearchResult\n *\n * @param {number} rank where this SearchResult ranks in the results\n * @param {event-context.EventContext} context the matching event and its\n * context\n *\n * @constructor\n */\n constructor(public readonly rank: number, public readonly context: EventContext) {}\n}\n",
|
||||
"/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventEmitter } from \"events\";\nimport { MatrixClient } from \"../matrix\";\nimport { MatrixEvent } from \"./event\";\nimport { EventTimelineSet } from './event-timeline-set';\nimport { Room } from './room';\n\n/**\n * @experimental\n */\nexport class Thread extends EventEmitter {\n /**\n * A reference to the event ID at the top of the thread\n */\n private root: string;\n /**\n * A reference to all the events ID at the bottom of the threads\n */\n public tail = new Set<string>();\n private _timelineSet: EventTimelineSet;\n\n constructor(\n events: MatrixEvent[] = [],\n public readonly room: Room,\n public readonly client: MatrixClient,\n ) {\n super();\n this._timelineSet = new EventTimelineSet(room, {\n unstableClientRelationAggregation: true,\n timelineSupport: true,\n });\n events.forEach(event => this.addEvent(event));\n }\n\n /**\n * Add an event to the thread and updates\n * the tail/root references if needed\n * Will fire \"Thread.update\"\n * @param event The event to add\n */\n public async addEvent(event: MatrixEvent): Promise<void> {\n if (this._timelineSet.findEventById(event.getId()) || event.status !== null) {\n return;\n }\n\n if (this.tail.has(event.replyEventId)) {\n this.tail.delete(event.replyEventId);\n }\n this.tail.add(event.getId());\n\n if (!event.replyEventId || !this._timelineSet.findEventById(event.replyEventId)) {\n this.root = event.getId();\n }\n\n event.setThread(this);\n this._timelineSet.addLiveEvent(event);\n\n if (this.ready) {\n this.client.decryptEventIfNeeded(event, {});\n this.emit(\"Thread.update\", this);\n } else {\n this.emit(\"Thread.update\", this);\n }\n }\n\n /**\n * Completes the reply chain with all events\n * missing from the current sync data\n * Will fire \"Thread.ready\"\n */\n public async fetchReplyChain(): Promise<void> {\n if (!this.ready) {\n let mxEvent = this.room.findEventById(this.rootEvent.replyEventId);\n if (!mxEvent) {\n mxEvent = await this.fetchEventById(\n this.rootEvent.getRoomId(),\n this.rootEvent.replyEventId,\n );\n }\n\n this.addEvent(mxEvent);\n if (mxEvent.replyEventId) {\n await this.fetchReplyChain();\n } else {\n await this.decryptEvents();\n this.emit(\"Thread.ready\", this);\n }\n }\n }\n\n private async decryptEvents(): Promise<void> {\n await Promise.allSettled(\n Array.from(this._timelineSet.getLiveTimeline().getEvents()).map(event => {\n return this.client.decryptEventIfNeeded(event, {});\n }),\n );\n }\n\n /**\n * Fetches an event over the network\n */\n private async fetchEventById(roomId: string, eventId: string): Promise<MatrixEvent> {\n const response = await this.client.http.authedRequest(\n undefined,\n \"GET\",\n `/rooms/${roomId}/event/${eventId}`,\n );\n return new MatrixEvent(response);\n }\n\n /**\n * Finds an event by ID in the current thread\n */\n public findEventById(eventId: string) {\n return this._timelineSet.findEventById(eventId);\n }\n\n /**\n * Determines thread's ready status\n */\n public get ready(): boolean {\n return this.rootEvent.replyEventId === undefined;\n }\n\n /**\n * The thread ID, which is the same as the root event ID\n */\n public get id(): string {\n return this.root;\n }\n\n /**\n * The thread root event\n */\n public get rootEvent(): MatrixEvent {\n return this.findEventById(this.root);\n }\n\n /**\n * The number of messages in the thread\n */\n public get length(): number {\n return this._timelineSet.getLiveTimeline().getEvents().length;\n }\n\n /**\n * A set of mxid participating to the thread\n */\n public get participants(): Set<string> {\n const participants = new Set<string>();\n this._timelLine truncated
|
||||
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/user\n */\n\nimport { EventEmitter } from \"events\";\n\nimport { MatrixEvent } from \"./event\";\n\nexport class User extends EventEmitter {\n // eslint-disable-next-line camelcase\n private modified: number;\n\n // XXX these should be read-only\n public displayName: string;\n public rawDisplayName: string;\n public avatarUrl: string;\n public presenceStatusMsg: string = null;\n public presence = \"offline\";\n public lastActiveAgo = 0;\n public lastPresenceTs = 0;\n public currentlyActive = false;\n public events: {\n presence?: MatrixEvent;\n profile?: MatrixEvent;\n } = {\n presence: null,\n profile: null,\n };\n // eslint-disable-next-line camelcase\n public unstable_statusMessage = \"\";\n\n /**\n * Construct a new User. A User must have an ID and can optionally have extra\n * information associated with it.\n * @constructor\n * @param {string} userId Required. The ID of this user.\n * @prop {string} userId The ID of the user.\n * @prop {Object} info The info object supplied in the constructor.\n * @prop {string} displayName The 'displayname' of the user if known.\n * @prop {string} avatarUrl The 'avatar_url' of the user if known.\n * @prop {string} presence The presence enum if known.\n * @prop {string} presenceStatusMsg The presence status message if known.\n * @prop {Number} lastActiveAgo The time elapsed in ms since the user interacted\n * proactively with the server, or we saw a message from the user\n * @prop {Number} lastPresenceTs Timestamp (ms since the epoch) for when we last\n * received presence data for this user. We can subtract\n * lastActiveAgo from this to approximate an absolute value for\n * when a user was last active.\n * @prop {Boolean} currentlyActive Whether we should consider lastActiveAgo to be\n * an approximation and that the user should be seen as active 'now'\n * @prop {string} unstable_statusMessage The status message for the user, if known. This is\n * different from the presenceStatusMsg in that this is not tied to\n * the user's presence, and should be represented differently.\n * @prop {Object} events The events describing this user.\n * @prop {MatrixEvent} events.presence The m.presence event for this user.\n */\n constructor(public readonly userId: string) {\n super();\n this.displayName = userId;\n this.rawDisplayName = userId;\n this.avatarUrl = null;\n this.updateModifiedTime();\n }\n\n /**\n * Update this User with the given presence event. May fire \"User.presence\",\n * \"User.avatarUrl\" and/or \"User.displayName\" if this event updates this user's\n * properties.\n * @param {MatrixEvent} event The <code>m.presence</code> event.\n * @fires module:client~MatrixClient#event:\"User.presence\"\n * @fires module:client~MatrixClient#event:\"User.displayName\"\n * @fires module:client~MatrixClient#event:\"User.avatarUrl\"\n */\n public setPresenceEvent(event: MatrixEvent): void {\n if (event.getType() !== \"m.presence\") {\n return;\n }\n const firstFire = this.events.presence === null;\n this.events.presence = event;\n\n const eventsToFire = [];\n if (event.getContent().presence !== this.presence || firstFire) {\n eventsToFire.push(\"User.presence\");\n }\n if (event.getContent().avatar_url &&\n event.getContent().avatar_url !== this.avatarUrl) {\n eventsToFire.push(\"User.avatarUrl\");\n }\n if (event.getContent().displayname &&\n event.getContent().displayname !== this.displayName) {\n eventsToFire.push(\"User.displayName\");\n }\n if (event.getContent().currently_active !== undefined &&\n event.getContent().currently_active !== this.currentlyActive) {\n eventsToFire.push(\"User.currentlyActive\");\n }\n\n this.presence = event.getContent().presence;\n eventsToFire.push(\"User.lastPresenceTs\");\n\n if (event.getContent().status_msg) {\n this.presenceStatusMsg = event.getContent(Line truncated
|
||||
"/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { escapeRegExp, globToRegexp, isNullOrUndefined } from \"./utils\";\nimport { logger } from './logger';\n\n/**\n * @module pushprocessor\n */\n\nconst RULEKINDS_IN_ORDER = ['override', 'content', 'room', 'sender', 'underride'];\n\n// The default override rules to apply to the push rules that arrive from the server.\n// We do this for two reasons:\n// 1. Synapse is unlikely to send us the push rule in an incremental sync - see\n// https://github.com/matrix-org/synapse/pull/4867#issuecomment-481446072 for\n// more details.\n// 2. We often want to start using push rules ahead of the server supporting them,\n// and so we can put them here.\nconst DEFAULT_OVERRIDE_RULES = [\n {\n // For homeservers which don't support MSC1930 yet\n rule_id: \".m.rule.tombstone\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: \"event_match\",\n key: \"type\",\n pattern: \"m.room.tombstone\",\n },\n {\n kind: \"event_match\",\n key: \"state_key\",\n pattern: \"\",\n },\n ],\n actions: [\n \"notify\",\n {\n set_tweak: \"highlight\",\n value: true,\n },\n ],\n },\n {\n // For homeservers which don't support MSC2153 yet\n rule_id: \".m.rule.reaction\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: \"event_match\",\n key: \"type\",\n pattern: \"m.reaction\",\n },\n ],\n actions: [\n \"dont_notify\",\n ],\n },\n];\n\n/**\n * Construct a Push Processor.\n * @constructor\n * @param {Object} client The Matrix client object to use\n */\nexport function PushProcessor(client) {\n const cachedGlobToRegex = {\n // $glob: RegExp,\n };\n\n const matchingRuleFromKindSet = (ev, kindset) => {\n for (let ruleKindIndex = 0;\n ruleKindIndex < RULEKINDS_IN_ORDER.length;\n ++ruleKindIndex) {\n const kind = RULEKINDS_IN_ORDER[ruleKindIndex];\n const ruleset = kindset[kind];\n if (!ruleset) {\n continue;\n }\n\n for (let ruleIndex = 0; ruleIndex < ruleset.length; ++ruleIndex) {\n const rule = ruleset[ruleIndex];\n if (!rule.enabled) {\n continue;\n }\n\n const rawrule = templateRuleToRaw(kind, rule);\n if (!rawrule) {\n continue;\n }\n\n if (this.ruleMatchesEvent(rawrule, ev)) {\n rule.kind = kind;\n return rule;\n }\n }\n }\n return null;\n };\n\n const templateRuleToRaw = function(kind, tprule) {\n const rawrule = {\n 'rule_id': tprule.rule_id,\n 'actions': tprule.actions,\n 'conditions': [],\n };\n switch (kind) {\n case 'underride':\n case 'override':\n rawrule.conditions = tprule.conditions;\n break;\n case 'room':\n if (!tprule.rule_id) {\n return null;\n }\n rawrule.conditions.push({\n 'kind': 'event_match',\n 'key': 'room_id',\n 'value': tprule.rule_id,\n });\n break;\n case 'sender':\n if (!tprule.rule_id) {\n return null;\n }\n rawrule.conditions.push({\n 'kind': 'event_match',\n 'key': 'user_id',\n 'value': tprule.rule_id,\n });\n break;\n case 'content':\n if (!tprule.pattern) {\n return null;\n }\n rawrule.conditions.push({\n 'kind': 'event_match',\n 'key': 'content.body',\n 'pattern': tprule.pattern,\n });\n break;\n }\n return rawrule;\n }Line truncated
|
||||
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { escapeRegExp, globToRegexp, isNullOrUndefined } from \"./utils\";\nimport { logger } from './logger';\nimport { MatrixClient } from \"./client\";\nimport { MatrixEvent } from \"./models/event\";\nimport {\n ConditionKind,\n IAnnotatedPushRule,\n IContainsDisplayNameCondition,\n IEventMatchCondition,\n IPushRule,\n IPushRules,\n IRoomMemberCountCondition,\n ISenderNotificationPermissionCondition,\n PushRuleAction,\n PushRuleActionName,\n PushRuleCondition,\n PushRuleKind,\n PushRuleSet,\n TweakName,\n} from \"./@types/PushRules\";\n\n/**\n * @module pushprocessor\n */\n\nconst RULEKINDS_IN_ORDER = [\n PushRuleKind.Override,\n PushRuleKind.ContentSpecific,\n PushRuleKind.RoomSpecific,\n PushRuleKind.SenderSpecific,\n PushRuleKind.Underride,\n];\n\n// The default override rules to apply to the push rules that arrive from the server.\n// We do this for two reasons:\n// 1. Synapse is unlikely to send us the push rule in an incremental sync - see\n// https://github.com/matrix-org/synapse/pull/4867#issuecomment-481446072 for\n// more details.\n// 2. We often want to start using push rules ahead of the server supporting them,\n// and so we can put them here.\nconst DEFAULT_OVERRIDE_RULES: IPushRule[] = [\n {\n // For homeservers which don't support MSC1930 yet\n rule_id: \".m.rule.tombstone\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventMatch,\n key: \"type\",\n pattern: \"m.room.tombstone\",\n },\n {\n kind: ConditionKind.EventMatch,\n key: \"state_key\",\n pattern: \"\",\n },\n ],\n actions: [\n PushRuleActionName.Notify,\n {\n set_tweak: TweakName.Highlight,\n value: true,\n },\n ],\n },\n {\n // For homeservers which don't support MSC2153 yet\n rule_id: \".m.rule.reaction\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventMatch,\n key: \"type\",\n pattern: \"m.reaction\",\n },\n ],\n actions: [\n PushRuleActionName.DontNotify,\n ],\n },\n];\n\nexport interface IActionsObject {\n notify: boolean;\n tweaks: Partial<Record<TweakName, any>>;\n}\n\nexport class PushProcessor {\n /**\n * Construct a Push Processor.\n * @constructor\n * @param {Object} client The Matrix client object to use\n */\n constructor(private readonly client: MatrixClient) {}\n\n /**\n * Convert a list of actions into a object with the actions as keys and their values\n * eg. [ 'notify', { set_tweak: 'sound', value: 'default' } ]\n * becomes { notify: true, tweaks: { sound: 'default' } }\n * @param {array} actionList The actions list\n *\n * @return {object} A object with key 'notify' (true or false) and an object of actions\n */\n public static actionListToActionsObject(actionList: PushRuleAction[]): IActionsObject {\n const actionObj: IActionsObject = { notify: false, tweaks: {} };\n for (let i = 0; i < actionList.length; ++i) {\n const action = actionList[i];\n if (action === PushRuleActionName.Notify) {\n actionObj.notify = true;\n } else if (typeof action === 'object') {\n if (action.value === undefined) {\n action.value = true;\n }\n actionObj.tweaks[action.set_tweak] = action.value;\n }\n }\n return actionObj;\n }\n\n /**\n * Rewrites conditions on a client's push rules to match the defaults\n * where applicable. Useful for upgrading push rules to more strict\n * conditions when the server is falling behind on defaults.\n * @param {object} incomingRules The client's existing push rules\n * @returns {object} The rewritten rules\n */\n public static rewriteDefaultRules(incomingRules: IPushRules): IPushRules {\n let newRules: IPushRules = JSON.parse(JSON.stringify(incomingRules)); // deep clone\n\n // These lines are mostly to make the Line truncated
|
||||
"/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nconst LOWERCASE = \"abcdefghijklmnopqrstuvwxyz\";\nconst UPPERCASE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst DIGITS = \"0123456789\";\n\nexport function randomString(len: number): string {\n return randomStringFrom(len, UPPERCASE + LOWERCASE + DIGITS);\n}\n\nexport function randomLowercaseString(len: number): string {\n return randomStringFrom(len, LOWERCASE);\n}\n\nexport function randomUppercaseString(len: number): string {\n return randomStringFrom(len, UPPERCASE);\n}\n\nfunction randomStringFrom(len: number, chars: string): string {\n let ret = \"\";\n\n for (let i = 0; i < len; ++i) {\n ret += chars.charAt(Math.floor(Math.random() * chars.length));\n }\n\n return ret;\n}\n",
|
||||
"/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/* A re-implementation of the javascript callback functions (setTimeout,\n * clearTimeout; setInterval and clearInterval are not yet implemented) which\n * try to improve handling of large clock jumps (as seen when\n * suspending/resuming the system).\n *\n * In particular, if a timeout would have fired while the system was suspended,\n * it will instead fire as soon as possible after resume.\n */\n\nimport { logger } from './logger';\n\n// we schedule a callback at least this often, to check if we've missed out on\n// some wall-clock time due to being suspended.\nconst TIMER_CHECK_PERIOD_MS = 1000;\n\n// counter, for making up ids to return from setTimeout\nlet _count = 0;\n\n// the key for our callback with the real global.setTimeout\nlet _realCallbackKey;\n\n// a sorted list of the callbacks to be run.\n// each is an object with keys [runAt, func, params, key].\nconst _callbackList = [];\n\n// var debuglog = logger.log.bind(logger);\nconst debuglog = function() {};\n\n/**\n * Replace the function used by this module to get the current time.\n *\n * Intended for use by the unit tests.\n *\n * @param {function} [f] function which should return a millisecond counter\n *\n * @internal\n */\nexport function setNow(f) {\n _now = f || Date.now;\n}\nlet _now = Date.now;\n\n/**\n * reimplementation of window.setTimeout, which will call the callback if\n * the wallclock time goes past the deadline.\n *\n * @param {function} func callback to be called after a delay\n * @param {Number} delayMs number of milliseconds to delay by\n *\n * @return {Number} an identifier for this callback, which may be passed into\n * clearTimeout later.\n */\nexport function setTimeout(func, delayMs) {\n delayMs = delayMs || 0;\n if (delayMs < 0) {\n delayMs = 0;\n }\n\n const params = Array.prototype.slice.call(arguments, 2);\n const runAt = _now() + delayMs;\n const key = _count++;\n debuglog(\"setTimeout: scheduling cb\", key, \"at\", runAt,\n \"(delay\", delayMs, \")\");\n const data = {\n runAt: runAt,\n func: func,\n params: params,\n key: key,\n };\n\n // figure out where it goes in the list\n const idx = binarySearch(\n _callbackList, function(el) {\n return el.runAt - runAt;\n },\n );\n\n _callbackList.splice(idx, 0, data);\n _scheduleRealCallback();\n\n return key;\n}\n\n/**\n * reimplementation of window.clearTimeout, which mirrors setTimeout\n *\n * @param {Number} key result from an earlier setTimeout call\n */\nexport function clearTimeout(key) {\n if (_callbackList.length === 0) {\n return;\n }\n\n // remove the element from the list\n let i;\n for (i = 0; i < _callbackList.length; i++) {\n const cb = _callbackList[i];\n if (cb.key == key) {\n _callbackList.splice(i, 1);\n break;\n }\n }\n\n // iff it was the first one in the list, reschedule our callback.\n if (i === 0) {\n _scheduleRealCallback();\n }\n}\n\n// use the real global.setTimeout to schedule a callback to _runCallbacks.\nfunction _scheduleRealCallback() {\n if (_realCallbackKey) {\n global.clearTimeout(_realCallbackKey);\n }\n\n const first = _callbackList[0];\n\n if (!first) {\n debuglog(\"_scheduleRealCallback: no more callbacks, not rescheduling\");\n return;\n }\n\n const now = _now();\n const delayMs = Math.min(first.runAt - now, TIMER_CHECK_PERIOD_MS);\n\n debuglog(\"_scheduleRealCallback: now:\", now, \"delay:\", delayMs);\n _realCallbackKey = global.setTimeout(_runCallbacks, delayMs);\n}\n\nfunction _runCallbacks() {\n let cb;\n const now = _now();\n debuglog(\"_runCallbacks: now:\", now);\n\n // get the list of things to call\n const callbacksToRun = [];\n while (true) {\n const first = _callbackList[0];\n if (!first || first.runAt > now) {\n break;\n }\n cb = _callbackList.shift();\n debuglog(\"_runCallbacks: popping\", cb.key);\n callbacksToRun.push(cb);\n }\n\n // reschedule the real callback before running our functions, to\n // keep the codepaths the same whether or not our functions\n // register their own setTimeouts.\n _scheduleRealCallback();\n\n for (let i = Line truncated
|
||||
"/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module which manages queuing, scheduling and retrying\n * of requests.\n * @module scheduler\n */\nimport * as utils from \"./utils\";\nimport { logger } from './logger';\n\nconst DEBUG = false; // set true to enable console logging.\n\n/**\n * Construct a scheduler for Matrix. Requires\n * {@link module:scheduler~MatrixScheduler#setProcessFunction} to be provided\n * with a way of processing events.\n * @constructor\n * @param {module:scheduler~retryAlgorithm} retryAlgorithm Optional. The retry\n * algorithm to apply when determining when to try to send an event again.\n * Defaults to {@link module:scheduler~MatrixScheduler.RETRY_BACKOFF_RATELIMIT}.\n * @param {module:scheduler~queueAlgorithm} queueAlgorithm Optional. The queuing\n * algorithm to apply when determining which events should be sent before the\n * given event. Defaults to {@link module:scheduler~MatrixScheduler.QUEUE_MESSAGES}.\n */\nexport function MatrixScheduler(retryAlgorithm, queueAlgorithm) {\n this.retryAlgorithm = retryAlgorithm || MatrixScheduler.RETRY_BACKOFF_RATELIMIT;\n this.queueAlgorithm = queueAlgorithm || MatrixScheduler.QUEUE_MESSAGES;\n this._queues = {\n // queueName: [{\n // event: MatrixEvent, // event to send\n // defer: Deferred, // defer to resolve/reject at the END of the retries\n // attempts: Number // number of times we've called processFn\n // }, ...]\n };\n this._activeQueues = [];\n this._procFn = null;\n}\n\n/**\n * Retrieve a queue based on an event. The event provided does not need to be in\n * the queue.\n * @param {MatrixEvent} event An event to get the queue for.\n * @return {?Array<MatrixEvent>} A shallow copy of events in the queue or null.\n * Modifying this array will not modify the list itself. Modifying events in\n * this array <i>will</i> modify the underlying event in the queue.\n * @see MatrixScheduler.removeEventFromQueue To remove an event from the queue.\n */\nMatrixScheduler.prototype.getQueueForEvent = function(event) {\n const name = this.queueAlgorithm(event);\n if (!name || !this._queues[name]) {\n return null;\n }\n return this._queues[name].map(function(obj) {\n return obj.event;\n });\n};\n\n/**\n * Remove this event from the queue. The event is equal to another event if they\n * have the same ID returned from event.getId().\n * @param {MatrixEvent} event The event to remove.\n * @return {boolean} True if this event was removed.\n */\nMatrixScheduler.prototype.removeEventFromQueue = function(event) {\n const name = this.queueAlgorithm(event);\n if (!name || !this._queues[name]) {\n return false;\n }\n let removed = false;\n utils.removeElement(this._queues[name], function(element) {\n if (element.event.getId() === event.getId()) {\n // XXX we should probably reject the promise?\n // https://github.com/matrix-org/matrix-js-sdk/issues/496\n removed = true;\n return true;\n }\n });\n return removed;\n};\n\n/**\n * Set the process function. Required for events in the queue to be processed.\n * If set after events have been added to the queue, this will immediately start\n * processing them.\n * @param {module:scheduler~processFn} fn The function that can process events\n * in the queue.\n */\nMatrixScheduler.prototype.setProcessFunction = function(fn) {\n this._procFn = fn;\n _startProcessingQueues(this);\n};\n\n/**\n * Queue an event if it is required and start processing queues.\n * @param {MatrixEvent} event The event that may be queued.\n * @return {?Promise} A promise if the event was queued, which will be\n * resolved or rejected in due time, else null.\n */\nMatrixScheduler.prototype.queueEvent = function(event) {\n const queueName = this.queueAlgorithm(event);\n if (!queueName) {\n return null;\n }\n // add the event to the queue and make a deferred for it.\n if (!this._queues[queueName]) {\n this._queues[queueName] = [];\n }\n const defer = utils.defer();\n this._queues[queueName].push({\n event: event,\n defer: defer,\n attempts: 0,\n });\n debuglog(\n \"Queue algorithm dumped event %s into queue '%s'\",\n event.getId(), queueName,\n );\n _startProcessingQueues(Line truncated
|
||||
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module which manages queuing, scheduling and retrying\n * of requests.\n * @module scheduler\n */\nimport * as utils from \"./utils\";\nimport { logger } from './logger';\nimport { MatrixEvent } from \"./models/event\";\nimport { EventType } from \"./@types/event\";\nimport { IDeferred } from \"./utils\";\nimport { MatrixError } from \"./http-api\";\nimport { ISendEventResponse } from \"./@types/requests\";\n\nconst DEBUG = false; // set true to enable console logging.\n\ninterface IQueueEntry<T> {\n event: MatrixEvent;\n defer: IDeferred<T>;\n attempts: number;\n}\n\ntype ProcessFunction<T> = (event: MatrixEvent) => Promise<T>;\n\n/**\n * Construct a scheduler for Matrix. Requires\n * {@link module:scheduler~MatrixScheduler#setProcessFunction} to be provided\n * with a way of processing events.\n * @constructor\n * @param {module:scheduler~retryAlgorithm} retryAlgorithm Optional. The retry\n * algorithm to apply when determining when to try to send an event again.\n * Defaults to {@link module:scheduler~MatrixScheduler.RETRY_BACKOFF_RATELIMIT}.\n * @param {module:scheduler~queueAlgorithm} queueAlgorithm Optional. The queuing\n * algorithm to apply when determining which events should be sent before the\n * given event. Defaults to {@link module:scheduler~MatrixScheduler.QUEUE_MESSAGES}.\n */\n// eslint-disable-next-line camelcase\nexport class MatrixScheduler<T = ISendEventResponse> {\n /**\n * Retries events up to 4 times using exponential backoff. This produces wait\n * times of 2, 4, 8, and 16 seconds (30s total) after which we give up. If the\n * failure was due to a rate limited request, the time specified in the error is\n * waited before being retried.\n * @param {MatrixEvent} event\n * @param {Number} attempts\n * @param {MatrixError} err\n * @return {Number}\n * @see module:scheduler~retryAlgorithm\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public static RETRY_BACKOFF_RATELIMIT(event: MatrixEvent, attempts: number, err: MatrixError): number {\n if (err.httpStatus === 400 || err.httpStatus === 403 || err.httpStatus === 401) {\n // client error; no amount of retrying with save you now.\n return -1;\n }\n // we ship with browser-request which returns { cors: rejected } when trying\n // with no connection, so if we match that, give up since they have no conn.\n if (err.cors === \"rejected\") {\n return -1;\n }\n\n // if event that we are trying to send is too large in any way then retrying won't help\n if (err.name === \"M_TOO_LARGE\") {\n return -1;\n }\n\n if (err.name === \"M_LIMIT_EXCEEDED\") {\n const waitTime = err.data.retry_after_ms;\n if (waitTime > 0) {\n return waitTime;\n }\n }\n if (attempts > 4) {\n return -1; // give up\n }\n return (1000 * Math.pow(2, attempts));\n }\n\n /**\n * Queues <code>m.room.message</code> events and lets other events continue\n * concurrently.\n * @param {MatrixEvent} event\n * @return {string}\n * @see module:scheduler~queueAlgorithm\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public static QUEUE_MESSAGES(event: MatrixEvent) {\n // enqueue messages or events that associate with another event (redactions and relations)\n if (event.getType() === EventType.RoomMessage || event.hasAssocation()) {\n // put these events in the 'message' queue.\n return \"message\";\n }\n // allow all other events continue concurrently.\n return null;\n }\n\n // queueName: [{\n // event: MatrixEvent, // event to send\n // defer: Deferred, // defer to resolve/reject at the END of the retries\n // attempts: Number // number of times we've called processFn\n // }, ...]\n private readonly queues: Record<string, IQueueEntry<T>[]> = {};\n private activeQueues: string[] = [];\n private procFn: ProcessFunction<T> = null;\n\n constructor(\n public readonly retryAlgorithm = MatrixScheduler.RETRY_BACKOFF_RATELIMIT,\n public readonly queueAlgorithm = MatrixScheduler.QUEUE_MESSAGES,\n ) {}\n\n /**\n * RLine truncated
|
||||
"/*\nCopyright 2019 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport enum SERVICE_TYPES {\n IS = 'SERVICE_TYPE_IS', // An identity server\n IM = 'SERVICE_TYPE_IM', // An integration manager\n}\n",
|
||||
"/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { IMinimalEvent, ISyncData, ISyncResponse, SyncAccumulator } from \"../sync-accumulator\";\nimport * as utils from \"../utils\";\nimport * as IndexedDBHelpers from \"../indexeddb-helpers\";\nimport { logger } from '../logger';\nimport { IEvent, IStartClientOpts } from \"..\";\nimport { ISavedSync } from \"./index\";\nimport { IIndexedDBBackend, UserTuple } from \"./indexeddb-backend\";\n\nconst VERSION = 3;\n\nfunction createDatabase(db: IDBDatabase): void {\n // Make user store, clobber based on user ID. (userId property of User objects)\n db.createObjectStore(\"users\", { keyPath: [\"userId\"] });\n\n // Make account data store, clobber based on event type.\n // (event.type property of MatrixEvent objects)\n db.createObjectStore(\"accountData\", { keyPath: [\"type\"] });\n\n // Make /sync store (sync tokens, room data, etc), always clobber (const key).\n db.createObjectStore(\"sync\", { keyPath: [\"clobber\"] });\n}\n\nfunction upgradeSchemaV2(db: IDBDatabase): void {\n const oobMembersStore = db.createObjectStore(\n \"oob_membership_events\", {\n keyPath: [\"room_id\", \"state_key\"],\n });\n oobMembersStore.createIndex(\"room\", \"room_id\");\n}\n\nfunction upgradeSchemaV3(db: IDBDatabase): void {\n db.createObjectStore(\"client_options\",\n { keyPath: [\"clobber\"] });\n}\n\n/**\n * Helper method to collect results from a Cursor and promiseify it.\n * @param {ObjectStore|Index} store The store to perform openCursor on.\n * @param {IDBKeyRange=} keyRange Optional key range to apply on the cursor.\n * @param {Function} resultMapper A function which is repeatedly called with a\n * Cursor.\n * Return the data you want to keep.\n * @return {Promise<T[]>} Resolves to an array of whatever you returned from\n * resultMapper.\n */\nfunction selectQuery<T>(\n store: IDBObjectStore,\n keyRange: IDBKeyRange | IDBValidKey | undefined,\n resultMapper: (cursor: IDBCursorWithValue) => T,\n): Promise<T[]> {\n const query = store.openCursor(keyRange);\n return new Promise((resolve, reject) => {\n const results = [];\n query.onerror = () => {\n reject(new Error(\"Query failed: \" + query.error));\n };\n // collect results\n query.onsuccess = () => {\n const cursor = query.result;\n if (!cursor) {\n resolve(results);\n return; // end of results\n }\n results.push(resultMapper(cursor));\n cursor.continue();\n };\n });\n}\n\nfunction txnAsPromise(txn: IDBTransaction): Promise<Event> {\n return new Promise((resolve, reject) => {\n txn.oncomplete = function(event) {\n resolve(event);\n };\n txn.onerror = function() {\n reject(txn.error);\n };\n });\n}\n\nfunction reqAsEventPromise(req: IDBRequest): Promise<Event> {\n return new Promise((resolve, reject) => {\n req.onsuccess = function(event) {\n resolve(event);\n };\n req.onerror = function() {\n reject(req.error);\n };\n });\n}\n\nfunction reqAsPromise(req: IDBRequest): Promise<IDBRequest> {\n return new Promise((resolve, reject) => {\n req.onsuccess = () => resolve(req);\n req.onerror = (err) => reject(err);\n });\n}\n\nfunction reqAsCursorPromise(req: IDBRequest<IDBCursor | null>): Promise<IDBCursor> {\n return reqAsEventPromise(req).then((event) => req.result);\n}\n\nexport class LocalIndexedDBStoreBackend implements IIndexedDBBackend {\n public static exists(indexedDB: IDBFactory, dbName: string): Promise<boolean> {\n dbName = \"matrix-js-sdk:\" + (dbName || \"default\");\n return IndexedDBHelpers.exists(indexedDB, dbName);\n }\n\n private readonly dbName: string;\n private readonly syncAccumulator: SyncAccumulator;\n private db: IDBDatabase = null;\n private disconnected = true;\n private _isNewlyCreated = false;\n\n /**\n * Does the actual reading from and writing to the indexeddb\n *\n * Construct a new Indexed Database store backend. This requires a call to\n * <code>connect()</code> before this store can be used.\n * @constructor\n * @param {Object} indexedDB The Indexed DB interface e.g\n * <code>window.indexedDB</code>\n * @param {string=} dLine truncated
|
||||
"/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from \"../logger\";\nimport { defer, IDeferred } from \"../utils\";\nimport { ISavedSync } from \"./index\";\nimport { IStartClientOpts } from \"../client\";\nimport { IEvent, ISyncResponse } from \"..\";\nimport { IIndexedDBBackend, UserTuple } from \"./indexeddb-backend\";\n\nexport class RemoteIndexedDBStoreBackend implements IIndexedDBBackend {\n private worker: Worker;\n private nextSeq = 0;\n // The currently in-flight requests to the actual backend\n private inFlight: Record<number, IDeferred<any>> = {}; // seq: promise\n // Once we start connecting, we keep the promise and re-use it\n // if we try to connect again\n private startPromise: Promise<void> = null;\n\n /**\n * An IndexedDB store backend where the actual backend sits in a web\n * worker.\n *\n * Construct a new Indexed Database store backend. This requires a call to\n * <code>connect()</code> before this store can be used.\n * @constructor\n * @param {Function} workerFactory Factory which produces a Worker\n * @param {string=} dbName Optional database name. The same name must be used\n * to open the same database.\n */\n constructor(\n private readonly workerFactory: () => Worker,\n private readonly dbName: string,\n ) {}\n\n /**\n * Attempt to connect to the database. This can fail if the user does not\n * grant permission.\n * @return {Promise} Resolves if successfully connected.\n */\n public connect(): Promise<void> {\n return this.ensureStarted().then(() => this.doCmd('connect'));\n }\n\n /**\n * Clear the entire database. This should be used when logging out of a client\n * to prevent mixing data between accounts.\n * @return {Promise} Resolved when the database is cleared.\n */\n public clearDatabase(): Promise<void> {\n return this.ensureStarted().then(() => this.doCmd('clearDatabase'));\n }\n\n /** @return {Promise<boolean>} whether or not the database was newly created in this session. */\n public isNewlyCreated(): Promise<boolean> {\n return this.doCmd('isNewlyCreated');\n }\n\n /**\n * @return {Promise} Resolves with a sync response to restore the\n * client state to where it was at the last save, or null if there\n * is no saved sync data.\n */\n public getSavedSync(): Promise<ISavedSync> {\n return this.doCmd('getSavedSync');\n }\n\n public getNextBatchToken(): Promise<string> {\n return this.doCmd('getNextBatchToken');\n }\n\n public setSyncData(syncData: ISyncResponse): Promise<void> {\n return this.doCmd('setSyncData', [syncData]);\n }\n\n public syncToDatabase(userTuples: UserTuple[]): Promise<void> {\n return this.doCmd('syncToDatabase', [userTuples]);\n }\n\n /**\n * Returns the out-of-band membership events for this room that\n * were previously loaded.\n * @param {string} roomId\n * @returns {event[]} the events, potentially an empty array if OOB loading didn't yield any new members\n * @returns {null} in case the members for this room haven't been stored yet\n */\n public getOutOfBandMembers(roomId: string): Promise<IEvent[] | null> {\n return this.doCmd('getOutOfBandMembers', [roomId]);\n }\n\n /**\n * Stores the out-of-band membership events for this room. Note that\n * it still makes sense to store an empty array as the OOB status for the room is\n * marked as fetched, and getOutOfBandMembers will return an empty array instead of null\n * @param {string} roomId\n * @param {event[]} membershipEvents the membership events to store\n * @returns {Promise} when all members have been stored\n */\n public setOutOfBandMembers(roomId: string, membershipEvents: IEvent[]): Promise<void> {\n return this.doCmd('setOutOfBandMembers', [roomId, membershipEvents]);\n }\n\n public clearOutOfBandMembers(roomId: string): Promise<void> {\n return this.doCmd('clearOutOfBandMembers', [roomId]);\n }\n\n public getClientOptions(): Promise<IStartClientOpts> {\n return this.doCmd('getClientOptions');\n }\n\n public storeClientOptions(options: IStartClientOpts): Promise<void> {\n return this.doCmd('storeClientOptions', [options]);\n }\n\n /**\n * Load all user presLine truncated
|
||||
"/*\nCopyright 2017 - 2021 Vector Creations Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/* eslint-disable @babel/no-invalid-this */\n\nimport { EventEmitter } from 'events';\n\nimport { MemoryStore, IOpts as IBaseOpts } from \"./memory\";\nimport { LocalIndexedDBStoreBackend } from \"./indexeddb-local-backend\";\nimport { RemoteIndexedDBStoreBackend } from \"./indexeddb-remote-backend\";\nimport { User } from \"../models/user\";\nimport { IEvent, MatrixEvent } from \"../models/event\";\nimport { logger } from '../logger';\nimport { ISavedSync } from \"./index\";\nimport { IIndexedDBBackend } from \"./indexeddb-backend\";\nimport { ISyncResponse } from \"../sync-accumulator\";\n\n/**\n * This is an internal module. See {@link IndexedDBStore} for the public class.\n * @module store/indexeddb\n */\n\n// If this value is too small we'll be writing very often which will cause\n// noticeable stop-the-world pauses. If this value is too big we'll be writing\n// so infrequently that the /sync size gets bigger on reload. Writing more\n// often does not affect the length of the pause since the entire /sync\n// response is persisted each time.\nconst WRITE_DELAY_MS = 1000 * 60 * 5; // once every 5 minutes\n\ninterface IOpts extends IBaseOpts {\n indexedDB: IDBFactory;\n dbName?: string;\n workerFactory?: () => Worker;\n}\n\nexport class IndexedDBStore extends MemoryStore {\n static exists(indexedDB: IDBFactory, dbName: string): Promise<boolean> {\n return LocalIndexedDBStoreBackend.exists(indexedDB, dbName);\n }\n\n public readonly backend: IIndexedDBBackend;\n\n private startedUp = false;\n private syncTs = 0;\n // Records the last-modified-time of each user at the last point we saved\n // the database, such that we can derive the set if users that have been\n // modified since we last saved.\n private userModifiedMap: Record<string, number> = {}; // user_id : timestamp\n private emitter = new EventEmitter();\n\n /**\n * Construct a new Indexed Database store, which extends MemoryStore.\n *\n * This store functions like a MemoryStore except it periodically persists\n * the contents of the store to an IndexedDB backend.\n *\n * All data is still kept in-memory but can be loaded from disk by calling\n * <code>startup()</code>. This can make startup times quicker as a complete\n * sync from the server is not required. This does not reduce memory usage as all\n * the data is eagerly fetched when <code>startup()</code> is called.\n * <pre>\n * let opts = { indexedDB: window.indexedDB, localStorage: window.localStorage };\n * let store = new IndexedDBStore(opts);\n * await store.startup(); // load from indexed db\n * let client = sdk.createClient({\n * store: store,\n * });\n * client.startClient();\n * client.on(\"sync\", function(state, prevState, data) {\n * if (state === \"PREPARED\") {\n * console.log(\"Started up, now with go faster stripes!\");\n * }\n * });\n * </pre>\n *\n * @constructor\n * @extends MemoryStore\n * @param {Object} opts Options object.\n * @param {Object} opts.indexedDB The Indexed DB interface e.g.\n * <code>window.indexedDB</code>\n * @param {string=} opts.dbName Optional database name. The same name must be used\n * to open the same database.\n * @param {string=} opts.workerScript Optional URL to a script to invoke a web\n * worker with to run IndexedDB queries on the web worker. The IndexedDbStoreWorker\n * class is provided for this purpose and requires the application to provide a\n * trivial wrapper script around it.\n * @param {Object=} opts.workerApi The webWorker API object. If omitted, the global Worker\n * object will be used if it exists.\n * @prop {IndexedDBStoreBackend} backend The backend instance. Call through to\n * this API if you need to perform specific indexeddb actions like deleting the\n * database.\n */\n constructor(opts: IOpts) {\n super(opts);\n\n if (!opts.indexedDB) {\n throw new Error('Missing required option: indexedDB');\n }\n\n if (opts.workerFactory) {\n this.backend = new RemoteIndexedDBStoreBackend(opts.workerFactory, opts.dbName);\n } else {\n this.backend = new LocalIndexedDBStoreBackend(opts.indexedDB, opts.dbName);\n }\n }\n\n public on = this.Line truncated
|
||||
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MemoryStore} for the public class.\n * @module store/memory\n */\n\nimport { EventType } from \"../@types/event\";\nimport { Group } from \"../models/group\";\nimport { Room } from \"../models/room\";\nimport { User } from \"../models/user\";\nimport { IEvent, MatrixEvent } from \"../models/event\";\nimport { RoomState } from \"../models/room-state\";\nimport { RoomMember } from \"../models/room-member\";\nimport { Filter } from \"../filter\";\nimport { ISavedSync, IStore } from \"./index\";\nimport { RoomSummary } from \"../models/room-summary\";\nimport { ISyncResponse } from \"../sync-accumulator\";\n\nfunction isValidFilterId(filterId: string): boolean {\n const isValidStr = typeof filterId === \"string\" &&\n !!filterId &&\n filterId !== \"undefined\" && // exclude these as we've serialized undefined in localStorage before\n filterId !== \"null\";\n\n return isValidStr || typeof filterId === \"number\";\n}\n\nexport interface IOpts {\n localStorage?: Storage;\n}\n\n/**\n * Construct a new in-memory data store for the Matrix Client.\n * @constructor\n * @param {Object=} opts Config options\n * @param {LocalStorage} opts.localStorage The local storage instance to persist\n * some forms of data such as tokens. Rooms will NOT be stored.\n */\nexport class MemoryStore implements IStore {\n private rooms: Record<string, Room> = {}; // roomId: Room\n private groups: Record<string, Group> = {}; // groupId: Group\n private users: Record<string, User> = {}; // userId: User\n private syncToken: string = null;\n // userId: {\n // filterId: Filter\n // }\n private filters: Record<string, Record<string, Filter>> = {};\n public accountData: Record<string, MatrixEvent> = {}; // type : content\n private readonly localStorage: Storage;\n private oobMembers: Record<string, IEvent[]> = {}; // roomId: [member events]\n private clientOptions = {};\n\n constructor(opts: IOpts = {}) {\n this.localStorage = opts.localStorage;\n }\n\n /**\n * Retrieve the token to stream from.\n * @return {string} The token or null.\n */\n public getSyncToken(): string | null {\n return this.syncToken;\n }\n\n /** @return {Promise<boolean>} whether or not the database was newly created in this session. */\n public isNewlyCreated(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n /**\n * Set the token to stream from.\n * @param {string} token The token to stream from.\n */\n public setSyncToken(token: string) {\n this.syncToken = token;\n }\n\n /**\n * Store the given room.\n * @param {Group} group The group to be stored\n */\n public storeGroup(group: Group) {\n this.groups[group.groupId] = group;\n }\n\n /**\n * Retrieve a group by its group ID.\n * @param {string} groupId The group ID.\n * @return {Group} The group or null.\n */\n public getGroup(groupId: string): Group | null {\n return this.groups[groupId] || null;\n }\n\n /**\n * Retrieve all known groups.\n * @return {Group[]} A list of groups, which may be empty.\n */\n public getGroups(): Group[] {\n return Object.values(this.groups);\n }\n\n /**\n * Store the given room.\n * @param {Room} room The room to be stored. All properties must be stored.\n */\n public storeRoom(room: Room) {\n this.rooms[room.roomId] = room;\n // add listeners for room member changes so we can keep the room member\n // map up-to-date.\n room.currentState.on(\"RoomState.members\", this.onRoomMember);\n // add existing members\n room.currentState.getMembers().forEach((m) => {\n this.onRoomMember(null, room.currentState, m);\n });\n }\n\n /**\n * Called when a room member in a room being tracked by this store has been\n * updated.\n * @param {MatrixEvent} event\n * @param {RoomState} state\n * @param {RoomMember} member\n */\n private onRoomMember = (event: MatrixEvent, state: RoomState, member: RoomMember) => {\n if (member.membership === \"invite\") {\n // We do NOT add invited members because people love to typo user IDs\n // which would then show up in these lists (!)\n Line truncated
|
||||
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MemoryStore} for the public class.\n * @module store/memory\n */\n\nimport { EventType } from \"../@types/event\";\nimport { Group } from \"../models/group\";\nimport { Room } from \"../models/room\";\nimport { User } from \"../models/user\";\nimport { IEvent, MatrixEvent } from \"../models/event\";\nimport { RoomState } from \"../models/room-state\";\nimport { RoomMember } from \"../models/room-member\";\nimport { Filter } from \"../filter\";\nimport { ISavedSync, IStore } from \"./index\";\nimport { RoomSummary } from \"../models/room-summary\";\nimport { ISyncResponse } from \"../sync-accumulator\";\n\nfunction isValidFilterId(filterId: string): boolean {\n const isValidStr = typeof filterId === \"string\" &&\n !!filterId &&\n filterId !== \"undefined\" && // exclude these as we've serialized undefined in localStorage before\n filterId !== \"null\";\n\n return isValidStr || typeof filterId === \"number\";\n}\n\nexport interface IOpts {\n localStorage?: Storage;\n}\n\n/**\n * Construct a new in-memory data store for the Matrix Client.\n * @constructor\n * @param {Object=} opts Config options\n * @param {LocalStorage} opts.localStorage The local storage instance to persist\n * some forms of data such as tokens. Rooms will NOT be stored.\n */\nexport class MemoryStore implements IStore {\n private rooms: Record<string, Room> = {}; // roomId: Room\n private groups: Record<string, Group> = {}; // groupId: Group\n private users: Record<string, User> = {}; // userId: User\n private syncToken: string = null;\n // userId: {\n // filterId: Filter\n // }\n private filters: Record<string, Record<string, Filter>> = {};\n public accountData: Record<string, MatrixEvent> = {}; // type : content\n private readonly localStorage: Storage;\n private oobMembers: Record<string, IEvent[]> = {}; // roomId: [member events]\n private clientOptions = {};\n\n constructor(opts: IOpts = {}) {\n this.localStorage = opts.localStorage;\n }\n\n /**\n * Retrieve the token to stream from.\n * @return {string} The token or null.\n */\n public getSyncToken(): string | null {\n return this.syncToken;\n }\n\n /** @return {Promise<boolean>} whether or not the database was newly created in this session. */\n public isNewlyCreated(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n /**\n * Set the token to stream from.\n * @param {string} token The token to stream from.\n */\n public setSyncToken(token: string) {\n this.syncToken = token;\n }\n\n /**\n * Store the given room.\n * @param {Group} group The group to be stored\n * @deprecated groups/communities never made it to the spec and support for them is being discontinued.\n */\n public storeGroup(group: Group) {\n this.groups[group.groupId] = group;\n }\n\n /**\n * Retrieve a group by its group ID.\n * @param {string} groupId The group ID.\n * @return {Group} The group or null.\n * @deprecated groups/communities never made it to the spec and support for them is being discontinued.\n */\n public getGroup(groupId: string): Group | null {\n return this.groups[groupId] || null;\n }\n\n /**\n * Retrieve all known groups.\n * @return {Group[]} A list of groups, which may be empty.\n * @deprecated groups/communities never made it to the spec and support for them is being discontinued.\n */\n public getGroups(): Group[] {\n return Object.values(this.groups);\n }\n\n /**\n * Store the given room.\n * @param {Room} room The room to be stored. All properties must be stored.\n */\n public storeRoom(room: Room) {\n this.rooms[room.roomId] = room;\n // add listeners for room member changes so we can keep the room member\n // map up-to-date.\n room.currentState.on(\"RoomState.members\", this.onRoomMember);\n // add existing members\n room.currentState.getMembers().forEach((m) => {\n this.onRoomMember(null, room.currentState, m);\n });\n }\n\n /**\n * Called when a room member in a room being tracked by this store has been\n * updated.\n * @param {MatrixEvent} event\n * @param {RoomState} state\n * @Line truncated
|
||||
"/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 New Vector Ltd\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module store/session/webstorage\n */\n\nimport * as utils from \"../../utils\";\nimport { logger } from '../../logger';\n\nconst DEBUG = false; // set true to enable console logging.\nconst E2E_PREFIX = \"session.e2e.\";\n\n/**\n * Construct a web storage session store, capable of storing account keys,\n * session keys and access tokens.\n * @constructor\n * @param {WebStorage} webStore A web storage implementation, e.g.\n * 'window.localStorage' or 'window.sessionStorage' or a custom implementation.\n * @throws if the supplied 'store' does not meet the Storage interface of the\n * WebStorage API.\n */\nexport function WebStorageSessionStore(webStore) {\n this.store = webStore;\n if (!utils.isFunction(webStore.getItem) ||\n !utils.isFunction(webStore.setItem) ||\n !utils.isFunction(webStore.removeItem) ||\n !utils.isFunction(webStore.key) ||\n typeof(webStore.length) !== 'number'\n ) {\n throw new Error(\n \"Supplied webStore does not meet the WebStorage API interface\",\n );\n }\n}\n\nWebStorageSessionStore.prototype = {\n /**\n * Remove the stored end to end account for the logged-in user.\n */\n removeEndToEndAccount: function() {\n this.store.removeItem(KEY_END_TO_END_ACCOUNT);\n },\n\n /**\n * Load the end to end account for the logged-in user.\n * Note that the end-to-end account is now stored in the\n * crypto store rather than here: this remains here so\n * old sessions can be migrated out of the session store.\n * @return {?string} Base64 encoded account.\n */\n getEndToEndAccount: function() {\n return this.store.getItem(KEY_END_TO_END_ACCOUNT);\n },\n\n /**\n * Retrieves the known devices for all users.\n * @return {object} A map from user ID to map of device ID to keys for the device.\n */\n getAllEndToEndDevices: function() {\n const prefix = keyEndToEndDevicesForUser('');\n const devices = {};\n for (let i = 0; i < this.store.length; ++i) {\n const key = this.store.key(i);\n const userId = key.substr(prefix.length);\n if (key.startsWith(prefix)) devices[userId] = getJsonItem(this.store, key);\n }\n return devices;\n },\n\n getEndToEndDeviceTrackingStatus: function() {\n return getJsonItem(this.store, KEY_END_TO_END_DEVICE_LIST_TRACKING_STATUS);\n },\n\n /**\n * Get the sync token corresponding to the device list.\n *\n * @return {String?} token\n */\n getEndToEndDeviceSyncToken: function() {\n return getJsonItem(this.store, KEY_END_TO_END_DEVICE_SYNC_TOKEN);\n },\n\n /**\n * Removes all end to end device data from the store\n */\n removeEndToEndDeviceData: function() {\n removeByPrefix(this.store, keyEndToEndDevicesForUser(''));\n removeByPrefix(this.store, KEY_END_TO_END_DEVICE_LIST_TRACKING_STATUS);\n removeByPrefix(this.store, KEY_END_TO_END_DEVICE_SYNC_TOKEN);\n },\n\n /**\n * Retrieve the end-to-end sessions between the logged-in user and another\n * device.\n * @param {string} deviceKey The public key of the other device.\n * @return {object} A map from sessionId to Base64 end-to-end session.\n */\n getEndToEndSessions: function(deviceKey) {\n return getJsonItem(this.store, keyEndToEndSessions(deviceKey));\n },\n\n /**\n * Retrieve all end-to-end sessions between the logged-in user and other\n * devices.\n * @return {object} A map of {deviceKey -> {sessionId -> session pickle}}\n */\n getAllEndToEndSessions: function() {\n const deviceKeys = getKeysWithPrefix(this.store, keyEndToEndSessions(''));\n const results = {};\n for (const k of deviceKeys) {\n const unprefixedKey = k.substr(keyEndToEndSessions('').length);\n results[unprefixedKey] = getJsonItem(this.store, k);\n }\n return results;\n },\n\n /**\n * Remove all end-to-end sessions from the store\n * This is used after migrating sessions awat from the sessions store.\n */\n removeAllEndToEndSessions: function() {\n removeByPrefix(this.store, keyEndToEndSessions(''));\n },\n\n /**\n *Line truncated
|
||||
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module.\n * @module store/stub\n */\n\nimport { EventType } from \"../@types/event\";\nimport { Group } from \"../models/group\";\nimport { Room } from \"../models/room\";\nimport { User } from \"../models/user\";\nimport { IEvent, MatrixEvent } from \"../models/event\";\nimport { Filter } from \"../filter\";\nimport { ISavedSync, IStore } from \"./index\";\nimport { RoomSummary } from \"../models/room-summary\";\nimport { ISyncResponse } from \"../sync-accumulator\";\n\n/**\n * Construct a stub store. This does no-ops on most store methods.\n * @constructor\n */\nexport class StubStore implements IStore {\n public readonly accountData = {}; // stub\n private fromToken: string = null;\n\n /** @return {Promise<boolean>} whether or not the database was newly created in this session. */\n public isNewlyCreated(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n /**\n * Get the sync token.\n * @return {string}\n */\n public getSyncToken(): string | null {\n return this.fromToken;\n }\n\n /**\n * Set the sync token.\n * @param {string} token\n */\n public setSyncToken(token: string) {\n this.fromToken = token;\n }\n\n /**\n * No-op.\n * @param {Group} group\n */\n public storeGroup(group: Group) {}\n\n /**\n * No-op.\n * @param {string} groupId\n * @return {null}\n */\n public getGroup(groupId: string): Group | null {\n return null;\n }\n\n /**\n * No-op.\n * @return {Array} An empty array.\n */\n public getGroups(): Group[] {\n return [];\n }\n\n /**\n * No-op.\n * @param {Room} room\n */\n public storeRoom(room: Room) {}\n\n /**\n * No-op.\n * @param {string} roomId\n * @return {null}\n */\n public getRoom(roomId: string): Room | null {\n return null;\n }\n\n /**\n * No-op.\n * @return {Array} An empty array.\n */\n public getRooms(): Room[] {\n return [];\n }\n\n /**\n * Permanently delete a room.\n * @param {string} roomId\n */\n public removeRoom(roomId: string) {\n return;\n }\n\n /**\n * No-op.\n * @return {Array} An empty array.\n */\n public getRoomSummaries(): RoomSummary[] {\n return [];\n }\n\n /**\n * No-op.\n * @param {User} user\n */\n public storeUser(user: User) {}\n\n /**\n * No-op.\n * @param {string} userId\n * @return {null}\n */\n public getUser(userId: string): User | null {\n return null;\n }\n\n /**\n * No-op.\n * @return {User[]}\n */\n public getUsers(): User[] {\n return [];\n }\n\n /**\n * No-op.\n * @param {Room} room\n * @param {integer} limit\n * @return {Array}\n */\n public scrollback(room: Room, limit: number): MatrixEvent[] {\n return [];\n }\n\n /**\n * Store events for a room.\n * @param {Room} room The room to store events for.\n * @param {Array<MatrixEvent>} events The events to store.\n * @param {string} token The token associated with these events.\n * @param {boolean} toStart True if these are paginated results.\n */\n public storeEvents(room: Room, events: MatrixEvent[], token: string, toStart: boolean) {}\n\n /**\n * Store a filter.\n * @param {Filter} filter\n */\n public storeFilter(filter: Filter) {}\n\n /**\n * Retrieve a filter.\n * @param {string} userId\n * @param {string} filterId\n * @return {?Filter} A filter or null.\n */\n public getFilter(userId: string, filterId: string): Filter | null {\n return null;\n }\n\n /**\n * Retrieve a filter ID with the given name.\n * @param {string} filterName The filter name.\n * @return {?string} The filter ID or null.\n */\n public getFilterIdByName(filterName: string): string | null {\n return null;\n }\n\n /**\n * Set a filter name to ID mapping.\n * @param {string} filterName\n * @param {string} filterId\n */\n public setFilterIdByName(filterName: string, filterId: string) {}\n\n /**\n * Store user-scoped account data events\n * @param {Array<MatrixEvent>} events The events to store.\n */\n public storeAccountDataEvents(events: MatLine truncated
|
||||
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module.\n * @module store/stub\n */\n\nimport { EventType } from \"../@types/event\";\nimport { Group } from \"../models/group\";\nimport { Room } from \"../models/room\";\nimport { User } from \"../models/user\";\nimport { IEvent, MatrixEvent } from \"../models/event\";\nimport { Filter } from \"../filter\";\nimport { ISavedSync, IStore } from \"./index\";\nimport { RoomSummary } from \"../models/room-summary\";\nimport { ISyncResponse } from \"../sync-accumulator\";\n\n/**\n * Construct a stub store. This does no-ops on most store methods.\n * @constructor\n */\nexport class StubStore implements IStore {\n public readonly accountData = {}; // stub\n private fromToken: string = null;\n\n /** @return {Promise<boolean>} whether or not the database was newly created in this session. */\n public isNewlyCreated(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n /**\n * Get the sync token.\n * @return {string}\n */\n public getSyncToken(): string | null {\n return this.fromToken;\n }\n\n /**\n * Set the sync token.\n * @param {string} token\n */\n public setSyncToken(token: string) {\n this.fromToken = token;\n }\n\n /**\n * No-op.\n * @param {Group} group\n * @deprecated groups/communities never made it to the spec and support for them is being discontinued.\n */\n public storeGroup(group: Group) {}\n\n /**\n * No-op.\n * @param {string} groupId\n * @return {null}\n * @deprecated groups/communities never made it to the spec and support for them is being discontinued.\n */\n public getGroup(groupId: string): Group | null {\n return null;\n }\n\n /**\n * No-op.\n * @return {Array} An empty array.\n * @deprecated groups/communities never made it to the spec and support for them is being discontinued.\n */\n public getGroups(): Group[] {\n return [];\n }\n\n /**\n * No-op.\n * @param {Room} room\n */\n public storeRoom(room: Room) {}\n\n /**\n * No-op.\n * @param {string} roomId\n * @return {null}\n */\n public getRoom(roomId: string): Room | null {\n return null;\n }\n\n /**\n * No-op.\n * @return {Array} An empty array.\n */\n public getRooms(): Room[] {\n return [];\n }\n\n /**\n * Permanently delete a room.\n * @param {string} roomId\n */\n public removeRoom(roomId: string) {\n return;\n }\n\n /**\n * No-op.\n * @return {Array} An empty array.\n */\n public getRoomSummaries(): RoomSummary[] {\n return [];\n }\n\n /**\n * No-op.\n * @param {User} user\n */\n public storeUser(user: User) {}\n\n /**\n * No-op.\n * @param {string} userId\n * @return {null}\n */\n public getUser(userId: string): User | null {\n return null;\n }\n\n /**\n * No-op.\n * @return {User[]}\n */\n public getUsers(): User[] {\n return [];\n }\n\n /**\n * No-op.\n * @param {Room} room\n * @param {integer} limit\n * @return {Array}\n */\n public scrollback(room: Room, limit: number): MatrixEvent[] {\n return [];\n }\n\n /**\n * Store events for a room.\n * @param {Room} room The room to store events for.\n * @param {Array<MatrixEvent>} events The events to store.\n * @param {string} token The token associated with these events.\n * @param {boolean} toStart True if these are paginated results.\n */\n public storeEvents(room: Room, events: MatrixEvent[], token: string, toStart: boolean) {}\n\n /**\n * Store a filter.\n * @param {Filter} filter\n */\n public storeFilter(filter: Filter) {}\n\n /**\n * Retrieve a filter.\n * @param {string} userId\n * @param {string} filterId\n * @return {?Filter} A filter or null.\n */\n public getFilter(userId: string, filterId: string): Filter | null {\n return null;\n }\n\n /**\n * Retrieve a filter ID with the given name.\n * @param {string} filterName The filter name.\n * @return {?string} The filter ID or null.\n */\n public getFilterIdByName(filterName: string): string | null {\n return null;\n }\n\n /**\n * Set a filter name to ID mappinLine truncated
|
||||
"/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link SyncAccumulator} for the public class.\n * @module sync-accumulator\n */\n\nimport { logger } from './logger';\nimport { deepCopy } from \"./utils\";\nimport { IContent, IUnsigned } from \"./models/event\";\nimport { IRoomSummary } from \"./models/room-summary\";\nimport { EventType } from \"./@types/event\";\n\ninterface IOpts {\n maxTimelineEntries?: number;\n}\n\nexport interface IMinimalEvent {\n content: IContent;\n type: EventType | string;\n}\n\nexport interface IEphemeral {\n events: IMinimalEvent[];\n}\n\n/* eslint-disable camelcase */\ninterface IUnreadNotificationCounts {\n highlight_count?: number;\n notification_count?: number;\n}\n\nexport interface IRoomEvent extends IMinimalEvent {\n event_id: string;\n sender: string;\n origin_server_ts: number;\n unsigned?: IUnsigned;\n /** @deprecated - legacy field */\n age?: number;\n}\n\nexport interface IStateEvent extends IRoomEvent {\n prev_content?: IContent;\n state_key: string;\n}\n\ninterface IState {\n events: IStateEvent[];\n}\n\nexport interface ITimeline {\n events: Array<IRoomEvent | IStateEvent>;\n limited?: boolean;\n prev_batch: string;\n}\n\nexport interface IJoinedRoom {\n summary: IRoomSummary;\n state: IState;\n timeline: ITimeline;\n ephemeral: IEphemeral;\n account_data: IAccountData;\n unread_notifications: IUnreadNotificationCounts;\n}\n\nexport interface IStrippedState {\n content: IContent;\n state_key: string;\n type: EventType | string;\n sender: string;\n}\n\nexport interface IInviteState {\n events: IStrippedState[];\n}\n\nexport interface IInvitedRoom {\n invite_state: IInviteState;\n}\n\nexport interface ILeftRoom {\n state: IState;\n timeline: ITimeline;\n account_data: IAccountData;\n}\n\nexport interface IRooms {\n [Category.Join]: Record<string, IJoinedRoom>;\n [Category.Invite]: Record<string, IInvitedRoom>;\n [Category.Leave]: Record<string, ILeftRoom>;\n}\n\ninterface IPresence {\n events: IMinimalEvent[];\n}\n\ninterface IAccountData {\n events: IMinimalEvent[];\n}\n\ninterface IToDeviceEvent {\n content: IContent;\n sender: string;\n type: string;\n}\n\ninterface IToDevice {\n events: IToDeviceEvent[];\n}\n\ninterface IDeviceLists {\n changed: string[];\n left: string[];\n}\n\nexport interface IGroups {\n [Category.Join]: object;\n [Category.Invite]: object;\n [Category.Leave]: object;\n}\n\nexport interface ISyncResponse {\n next_batch: string;\n rooms: IRooms;\n presence?: IPresence;\n account_data: IAccountData;\n to_device?: IToDevice;\n device_lists?: IDeviceLists;\n device_one_time_keys_count?: Record<string, number>;\n\n groups: IGroups; // unspecced\n}\n/* eslint-enable camelcase */\n\nexport enum Category {\n Invite = \"invite\",\n Leave = \"leave\",\n Join = \"join\",\n}\n\ninterface IRoom {\n _currentState: { [eventType: string]: { [stateKey: string]: IStateEvent } };\n _timeline: {\n event: IRoomEvent | IStateEvent;\n token: string | null;\n }[];\n _summary: Partial<IRoomSummary>;\n _accountData: { [eventType: string]: IMinimalEvent };\n _unreadNotifications: Partial<IUnreadNotificationCounts>;\n _readReceipts: {\n [userId: string]: {\n data: IMinimalEvent;\n eventId: string;\n };\n };\n}\n\nexport interface ISyncData {\n nextBatch: string;\n accountData: IMinimalEvent[];\n roomsData: IRooms;\n groupsData: IGroups;\n}\n\n/**\n * The purpose of this class is to accumulate /sync responses such that a\n * complete \"initial\" JSON response can be returned which accurately represents\n * the sum total of the /sync responses accumulated to date. It only handles\n * room data: that is, everything under the \"rooms\" top-level key.\n *\n * This class is used when persisting room data so a complete /sync response can\n * be loaded from disk and incremental syncs can be performed on the server,\n * rather than asking the server to do an initial sync on startup.\n */\nexport class SyncAccumulator {\n private accountData: Record<string, IMinimalEvent> = {}; // $event_type: Object\n private inviteRooms: Record<string, IInvitedRoom> = {}; // $roomId: { ... sync 'invite' json data ... }\n private joinRooLine truncated
|
||||
"/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// TODO: Merge this with sync.js once converted\n\nexport enum SyncState {\n Error = \"ERROR\",\n Prepared = \"PREPARED\",\n Stopped = \"STOPPED\",\n Syncing = \"SYNCING\",\n Catchup = \"CATCHUP\",\n Reconnecting = \"RECONNECTING\",\n}\n",
|
||||
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\n * TODO:\n * This class mainly serves to take all the syncing logic out of client.js and\n * into a separate file. It's all very fluid, and this class gut wrenches a lot\n * of MatrixClient props (e.g. http). Given we want to support WebSockets as\n * an alternative syncing API, we may want to have a proper syncing interface\n * for HTTP and WS at some point.\n */\n\nimport { User } from \"./models/user\";\nimport { NotificationCountType, Room } from \"./models/room\";\nimport { Group } from \"./models/group\";\nimport * as utils from \"./utils\";\nimport { IDeferred } from \"./utils\";\nimport { Filter } from \"./filter\";\nimport { EventTimeline } from \"./models/event-timeline\";\nimport { PushProcessor } from \"./pushprocessor\";\nimport { logger } from './logger';\nimport { InvalidStoreError } from './errors';\nimport { IStoredClientOpts, MatrixClient, PendingEventOrdering } from \"./client\";\nimport { SyncState } from \"./sync.api\";\nimport {\n Category,\n IInvitedRoom,\n IInviteState,\n IJoinedRoom,\n ILeftRoom,\n IStateEvent,\n IRoomEvent,\n IStrippedState,\n ISyncResponse,\n ITimeline,\n IEphemeral,\n IMinimalEvent,\n} from \"./sync-accumulator\";\nimport { MatrixEvent } from \"./models/event\";\nimport { MatrixError } from \"./http-api\";\nimport { ISavedSync } from \"./store\";\n\nconst DEBUG = true;\n\n// /sync requests allow you to set a timeout= but the request may continue\n// beyond that and wedge forever, so we need to track how long we are willing\n// to keep open the connection. This constant is *ADDED* to the timeout= value\n// to determine the max time we're willing to wait.\nconst BUFFER_PERIOD_MS = 80 * 1000;\n\n// Number of consecutive failed syncs that will lead to a syncState of ERROR as opposed\n// to RECONNECTING. This is needed to inform the client of server issues when the\n// keepAlive is successful but the server /sync fails.\nconst FAILED_SYNC_ERROR_THRESHOLD = 3;\n\nfunction getFilterName(userId: string, suffix?: string): string {\n // scope this on the user ID because people may login on many accounts\n // and they all need to be stored!\n return \"FILTER_SYNC_\" + userId + (suffix ? \"_\" + suffix : \"\");\n}\n\nfunction debuglog(...params) {\n if (!DEBUG) {\n return;\n }\n logger.log(...params);\n}\n\ninterface ISyncOptions {\n filterId?: string;\n hasSyncedBefore?: boolean;\n}\n\nexport interface ISyncStateData {\n error?: Error;\n oldSyncToken?: string;\n nextSyncToken?: string;\n catchingUp?: boolean;\n fromCache?: boolean;\n}\n\ninterface ISyncParams {\n filter?: string;\n timeout: number;\n since?: string;\n // eslint-disable-next-line camelcase\n full_state?: boolean;\n // eslint-disable-next-line camelcase\n set_presence?: \"offline\" | \"online\" | \"unavailable\";\n _cacheBuster?: string | number; // not part of the API itself\n}\n\n// http-api mangles an abort method onto its promises\ninterface IRequestPromise<T> extends Promise<T> {\n abort(): void;\n}\n\ntype WrappedRoom<T> = T & {\n room: Room;\n isBrandNewRoom: boolean;\n};\n\n/**\n * <b>Internal class - unstable.</b>\n * Construct an entity which is able to sync with a homeserver.\n * @constructor\n * @param {MatrixClient} client The matrix client instance to use.\n * @param {Object} opts Config options\n * @param {module:crypto=} opts.crypto Crypto manager\n * @param {Function=} opts.canResetEntireTimeline A function which is called\n * with a room ID and returns a boolean. It should return 'true' if the SDK can\n * SAFELY remove events from this room. It may not be safe to remove events if\n * there are other references to the timelines for this room.\n * Default: returns false.\n * @param {Boolean=} opts.disablePresence True to perform syncing without automatically\n * updating presence.\n */\nexport class SyncApi {\n private _peekRoom: Room = null;\n private currentSyncRequest: IRequestPromise<ISyncResponse> = null;\n private syncState: SyncState = null;\n private syncStateData: ISyncStateData = null; // additional data (eg. error object for failed sync)\n private catchingUp = false;\n private running = false;\n private keepAliveTimer: number = null;\n private connectionReturnedDefer: IDeferred<boolean> = null;\n private notifEvents: MatrixEvent[] = []; /Line truncated
|
||||
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\n * TODO:\n * This class mainly serves to take all the syncing logic out of client.js and\n * into a separate file. It's all very fluid, and this class gut wrenches a lot\n * of MatrixClient props (e.g. http). Given we want to support WebSockets as\n * an alternative syncing API, we may want to have a proper syncing interface\n * for HTTP and WS at some point.\n */\n\nimport { User } from \"./models/user\";\nimport { NotificationCountType, Room } from \"./models/room\";\nimport { Group } from \"./models/group\";\nimport * as utils from \"./utils\";\nimport { IDeferred } from \"./utils\";\nimport { Filter } from \"./filter\";\nimport { EventTimeline } from \"./models/event-timeline\";\nimport { PushProcessor } from \"./pushprocessor\";\nimport { logger } from './logger';\nimport { InvalidStoreError } from './errors';\nimport { IStoredClientOpts, MatrixClient, PendingEventOrdering } from \"./client\";\nimport { SyncState } from \"./sync.api\";\nimport {\n Category,\n IInvitedRoom,\n IInviteState,\n IJoinedRoom,\n ILeftRoom,\n IStateEvent,\n IRoomEvent,\n IStrippedState,\n ISyncResponse,\n ITimeline,\n IEphemeral,\n IMinimalEvent,\n} from \"./sync-accumulator\";\nimport { MatrixEvent } from \"./models/event\";\nimport { MatrixError } from \"./http-api\";\nimport { ISavedSync } from \"./store\";\nimport { EventType } from \"./@types/event\";\nimport { IPushRules } from \"./@types/PushRules\";\n\nconst DEBUG = true;\n\n// /sync requests allow you to set a timeout= but the request may continue\n// beyond that and wedge forever, so we need to track how long we are willing\n// to keep open the connection. This constant is *ADDED* to the timeout= value\n// to determine the max time we're willing to wait.\nconst BUFFER_PERIOD_MS = 80 * 1000;\n\n// Number of consecutive failed syncs that will lead to a syncState of ERROR as opposed\n// to RECONNECTING. This is needed to inform the client of server issues when the\n// keepAlive is successful but the server /sync fails.\nconst FAILED_SYNC_ERROR_THRESHOLD = 3;\n\nfunction getFilterName(userId: string, suffix?: string): string {\n // scope this on the user ID because people may login on many accounts\n // and they all need to be stored!\n return \"FILTER_SYNC_\" + userId + (suffix ? \"_\" + suffix : \"\");\n}\n\nfunction debuglog(...params) {\n if (!DEBUG) {\n return;\n }\n logger.log(...params);\n}\n\ninterface ISyncOptions {\n filterId?: string;\n hasSyncedBefore?: boolean;\n}\n\nexport interface ISyncStateData {\n error?: Error;\n oldSyncToken?: string;\n nextSyncToken?: string;\n catchingUp?: boolean;\n fromCache?: boolean;\n}\n\ninterface ISyncParams {\n filter?: string;\n timeout: number;\n since?: string;\n // eslint-disable-next-line camelcase\n full_state?: boolean;\n // eslint-disable-next-line camelcase\n set_presence?: \"offline\" | \"online\" | \"unavailable\";\n _cacheBuster?: string | number; // not part of the API itself\n}\n\n// http-api mangles an abort method onto its promises\ninterface IRequestPromise<T> extends Promise<T> {\n abort(): void;\n}\n\ntype WrappedRoom<T> = T & {\n room: Room;\n isBrandNewRoom: boolean;\n};\n\n/**\n * <b>Internal class - unstable.</b>\n * Construct an entity which is able to sync with a homeserver.\n * @constructor\n * @param {MatrixClient} client The matrix client instance to use.\n * @param {Object} opts Config options\n * @param {module:crypto=} opts.crypto Crypto manager\n * @param {Function=} opts.canResetEntireTimeline A function which is called\n * with a room ID and returns a boolean. It should return 'true' if the SDK can\n * SAFELY remove events from this room. It may not be safe to remove events if\n * there are other references to the timelines for this room.\n * Default: returns false.\n * @param {Boolean=} opts.disablePresence True to perform syncing without automatically\n * updating presence.\n */\nexport class SyncApi {\n private _peekRoom: Room = null;\n private currentSyncRequest: IRequestPromise<ISyncResponse> = null;\n private syncState: SyncState = null;\n private syncStateData: ISyncStateData = null; // additional data (eg. error object for failed sync)\n private catchingUp = false;\n private running = false;\n private keepAliveTimer: number = null;\n private Line truncated
|
||||
"/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/** @module timeline-window */\n\nimport { Direction, EventTimeline } from './models/event-timeline';\nimport { logger } from './logger';\nimport { MatrixClient } from \"./client\";\nimport { EventTimelineSet } from \"./models/event-timeline-set\";\nimport { MatrixEvent } from \"./models/event\";\n\n/**\n * @private\n */\nconst DEBUG = false;\n\n/**\n * @private\n */\nconst debuglog = DEBUG ? logger.log.bind(logger) : function() {};\n\n/**\n * the number of times we ask the server for more events before giving up\n *\n * @private\n */\nconst DEFAULT_PAGINATE_LOOP_LIMIT = 5;\n\ninterface IOpts {\n windowLimit?: number;\n}\n\nexport class TimelineWindow {\n private readonly windowLimit: number;\n // these will be TimelineIndex objects; they delineate the 'start' and\n // 'end' of the window.\n //\n // start.index is inclusive; end.index is exclusive.\n private start?: TimelineIndex = null;\n private end?: TimelineIndex = null;\n private eventCount = 0;\n\n /**\n * Construct a TimelineWindow.\n *\n * <p>This abstracts the separate timelines in a Matrix {@link\n * module:models/room|Room} into a single iterable thing. It keeps track of\n * the start and endpoints of the window, which can be advanced with the help\n * of pagination requests.\n *\n * <p>Before the window is useful, it must be initialised by calling {@link\n * module:timeline-window~TimelineWindow#load|load}.\n *\n * <p>Note that the window will not automatically extend itself when new events\n * are received from /sync; you should arrange to call {@link\n * module:timeline-window~TimelineWindow#paginate|paginate} on {@link\n * module:client~MatrixClient.event:\"Room.timeline\"|Room.timeline} events.\n *\n * @param {MatrixClient} client MatrixClient to be used for context/pagination\n * requests.\n *\n * @param {EventTimelineSet} timelineSet The timelineSet to track\n *\n * @param {Object} [opts] Configuration options for this window\n *\n * @param {number} [opts.windowLimit = 1000] maximum number of events to keep\n * in the window. If more events are retrieved via pagination requests,\n * excess events will be dropped from the other end of the window.\n *\n * @constructor\n */\n constructor(\n private readonly client: MatrixClient,\n private readonly timelineSet: EventTimelineSet,\n opts: IOpts = {},\n ) {\n this.windowLimit = opts.windowLimit || 1000;\n }\n\n /**\n * Initialise the window to point at a given event, or the live timeline\n *\n * @param {string} [initialEventId] If given, the window will contain the\n * given event\n * @param {number} [initialWindowSize = 20] Size of the initial window\n *\n * @return {Promise}\n */\n public load(initialEventId: string, initialWindowSize = 20): Promise<any> {\n // given an EventTimeline, find the event we were looking for, and initialise our\n // fields so that the event in question is in the middle of the window.\n const initFields = (timeline: EventTimeline) => {\n let eventIndex;\n\n const events = timeline.getEvents();\n\n if (!initialEventId) {\n // we were looking for the live timeline: initialise to the end\n eventIndex = events.length;\n } else {\n for (let i = 0; i < events.length; i++) {\n if (events[i].getId() == initialEventId) {\n eventIndex = i;\n break;\n }\n }\n\n if (eventIndex === undefined) {\n throw new Error(\"getEventTimeline result didn't include requested event\");\n }\n }\n\n const endIndex = Math.min(events.length,\n eventIndex + Math.ceil(initialWindowSize / 2));\n const startIndex = Math.max(0, endIndex - initialWindowSize);\n this.start = new TimelineIndex(timeline, startIndex - timeline.getBaseIndex());\n this.end = new TimelineIndex(timeline, endIndex - timeline.getBaseIndex());\n this.eventCount = endIndex - startIndex;\n };\n\n // We avoid delaying the resolution of the promiLine truncated
|
||||
"/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module.\n * @module utils\n */\n\nimport unhomoglyph from \"unhomoglyph\";\nimport promiseRetry from \"p-retry\";\nimport type NodeCrypto from \"crypto\";\n\n/**\n * Encode a dictionary of query parameters.\n * @param {Object} params A dict of key/values to encode e.g.\n * {\"foo\": \"bar\", \"baz\": \"taz\"}\n * @return {string} The encoded string e.g. foo=bar&baz=taz\n */\nexport function encodeParams(params: Record<string, string>): string {\n return new URLSearchParams(params).toString();\n}\n\nexport type QueryDict = Record<string, string | string[]>;\n\n/**\n * Decode a query string in `application/x-www-form-urlencoded` format.\n * @param {string} query A query string to decode e.g.\n * foo=bar&via=server1&server2\n * @return {Object} The decoded object, if any keys occurred multiple times\n * then the value will be an array of strings, else it will be an array.\n * This behaviour matches Node's qs.parse but is built on URLSearchParams\n * for native web compatibility\n */\nexport function decodeParams(query: string): QueryDict {\n const o: QueryDict = {};\n const params = new URLSearchParams(query);\n for (const key of params.keys()) {\n const val = params.getAll(key);\n o[key] = val.length === 1 ? val[0] : val;\n }\n return o;\n}\n\n/**\n * Encodes a URI according to a set of template variables. Variables will be\n * passed through encodeURIComponent.\n * @param {string} pathTemplate The path with template variables e.g. '/foo/$bar'.\n * @param {Object} variables The key/value pairs to replace the template\n * variables with. E.g. { \"$bar\": \"baz\" }.\n * @return {string} The result of replacing all template variables e.g. '/foo/baz'.\n */\nexport function encodeUri(pathTemplate: string,\n variables: Record<string, string>): string {\n for (const key in variables) {\n if (!variables.hasOwnProperty(key)) {\n continue;\n }\n pathTemplate = pathTemplate.replace(\n key, encodeURIComponent(variables[key]),\n );\n }\n return pathTemplate;\n}\n\n/**\n * The removeElement() method removes the first element in the array that\n * satisfies (returns true) the provided testing function.\n * @param {Array} array The array.\n * @param {Function} fn Function to execute on each value in the array, with the\n * function signature <code>fn(element, index, array)</code>. Return true to\n * remove this element and break.\n * @param {boolean} reverse True to search in reverse order.\n * @return {boolean} True if an element was removed.\n */\nexport function removeElement<T>(\n array: T[],\n fn: (t: T, i?: number, a?: T[]) => boolean,\n reverse?: boolean,\n) {\n let i;\n let removed;\n if (reverse) {\n for (i = array.length - 1; i >= 0; i--) {\n if (fn(array[i], i, array)) {\n removed = array[i];\n array.splice(i, 1);\n return removed;\n }\n }\n } else {\n for (i = 0; i < array.length; i++) {\n if (fn(array[i], i, array)) {\n removed = array[i];\n array.splice(i, 1);\n return removed;\n }\n }\n }\n return false;\n}\n\n/**\n * Checks if the given thing is a function.\n * @param {*} value The thing to check.\n * @return {boolean} True if it is a function.\n */\nexport function isFunction(value: any) {\n return Object.prototype.toString.call(value) === \"[object Function]\";\n}\n\n/**\n * Checks that the given object has the specified keys.\n * @param {Object} obj The object to check.\n * @param {string[]} keys The list of keys that 'obj' must have.\n * @throws If the object is missing keys.\n */\n// note using 'keys' here would shadow the 'keys' function defined above\nexport function checkObjectHasKeys(obj: object, keys: string[]) {\n for (let i = 0; i < keys.length; i++) {\n if (!obj.hasOwnProperty(keys[i])) {\n throw new Error(\"Missing required key: \" + keys[i]);\n }\n }\n}\n\n/**\n * Checks that the given object has no extra keys other than the specified ones.\n * @param {Object} obj The object to check.\n * @param {string[]} allowedKeys The list of allowed key names.\n * @throws If there are extra keys.\n */\nexport function checkObjectHasNoAddLine truncated
|
||||
"/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 New Vector Ltd\nCopyright 2019, 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link createNewMatrixCall} for the public API.\n * @module webrtc/call\n */\n\nimport { logger } from '../logger';\nimport { EventEmitter } from 'events';\nimport * as utils from '../utils';\nimport { MatrixEvent } from '../models/event';\nimport { EventType } from '../@types/event';\nimport { RoomMember } from '../models/room-member';\nimport { randomString } from '../randomstring';\nimport {\n MCallReplacesEvent,\n MCallAnswer,\n MCallOfferNegotiate,\n CallCapabilities,\n SDPStreamMetadataPurpose,\n SDPStreamMetadata,\n SDPStreamMetadataKey,\n MCallSDPStreamMetadataChanged,\n} from './callEventTypes';\nimport { CallFeed } from './callFeed';\n\n// events: hangup, error(err), replaced(call), state(state, oldState)\n\n/**\n * Fires whenever an error occurs when call.js encounters an issue with setting up the call.\n * <p>\n * The error given will have a code equal to either `MatrixCall.ERR_LOCAL_OFFER_FAILED` or\n * `MatrixCall.ERR_NO_USER_MEDIA`. `ERR_LOCAL_OFFER_FAILED` is emitted when the local client\n * fails to create an offer. `ERR_NO_USER_MEDIA` is emitted when the user has denied access\n * to their audio/video hardware.\n *\n * @event module:webrtc/call~MatrixCall#\"error\"\n * @param {Error} err The error raised by MatrixCall.\n * @example\n * matrixCall.on(\"error\", function(err){\n * console.error(err.code, err);\n * });\n */\n\ninterface CallOpts {\n roomId?: string;\n invitee?: string;\n client?: any; // Fix when client is TSified\n forceTURN?: boolean;\n turnServers?: Array<TurnServer>;\n}\n\ninterface TurnServer {\n urls: Array<string>;\n username?: string;\n password?: string;\n ttl?: number;\n}\n\ninterface AssertedIdentity {\n id: string;\n displayName: string;\n}\n\nexport enum CallState {\n Fledgling = 'fledgling',\n InviteSent = 'invite_sent',\n WaitLocalMedia = 'wait_local_media',\n CreateOffer = 'create_offer',\n CreateAnswer = 'create_answer',\n Connecting = 'connecting',\n Connected = 'connected',\n Ringing = 'ringing',\n Ended = 'ended',\n}\n\nexport enum CallType {\n Voice = 'voice',\n Video = 'video',\n}\n\nexport enum CallDirection {\n Inbound = 'inbound',\n Outbound = 'outbound',\n}\n\nexport enum CallParty {\n Local = 'local',\n Remote = 'remote',\n}\n\nexport enum CallEvent {\n Hangup = 'hangup',\n State = 'state',\n Error = 'error',\n Replaced = 'replaced',\n\n // The value of isLocalOnHold() has changed\n LocalHoldUnhold = 'local_hold_unhold',\n // The value of isRemoteOnHold() has changed\n RemoteHoldUnhold = 'remote_hold_unhold',\n // backwards compat alias for LocalHoldUnhold: remove in a major version bump\n HoldUnhold = 'hold_unhold',\n // Feeds have changed\n FeedsChanged = 'feeds_changed',\n\n AssertedIdentityChanged = 'asserted_identity_changed',\n}\n\nexport enum CallErrorCode {\n /** The user chose to end the call */\n UserHangup = 'user_hangup',\n\n /** An error code when the local client failed to create an offer. */\n LocalOfferFailed = 'local_offer_failed',\n /**\n * An error code when there is no local mic/camera to use. This may be because\n * the hardware isn't plugged in, or the user has explicitly denied access.\n */\n NoUserMedia = 'no_user_media',\n\n /**\n * Error code used when a call event failed to send\n * because unknown devices were present in the room\n */\n UnknownDevices = 'unknown_devices',\n\n /**\n * Error code used when we fail to send the invite\n * for some reason other than there being unknown devices\n */\n SendInvite = 'send_invite',\n\n /**\n * An answer could not be created\n */\n CreateAnswer = 'create_answer',\n\n /**\n * Error code used when we fail to send the answer\n * for some reason other than there being unknown devices\n */\n SendAnswer = 'send_answer',\n\n /**\n * The session description from the other side could not be set\n */\n SetRemoteDescription = 'set_remote_description',\n\n /**\n * The session description from this side could not be set\n */\n SetLocalDescription = 'set_local_description',\n\n /**\n * A different device answered the Line truncated
|
||||
"/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixEvent } from '../models/event';\nimport { logger } from '../logger';\nimport { createNewMatrixCall, MatrixCall, CallErrorCode, CallState, CallDirection } from './call';\nimport { EventType } from '../@types/event';\nimport { MatrixClient } from '../client';\n\n// Don't ring unless we'd be ringing for at least 3 seconds: the user needs some\n// time to press the 'accept' button\nconst RING_GRACE_PERIOD = 3000;\n\nexport class CallEventHandler {\n client: MatrixClient;\n calls: Map<string, MatrixCall>;\n callEventBuffer: MatrixEvent[];\n candidateEventsByCall: Map<string, Array<MatrixEvent>>;\n\n constructor(client: MatrixClient) {\n this.client = client;\n this.calls = new Map<string, MatrixCall>();\n // The sync code always emits one event at a time, so it will patiently\n // wait for us to finish processing a call invite before delivering the\n // next event, even if that next event is a hangup. We therefore accumulate\n // all our call events and then process them on the 'sync' event, ie.\n // each time a sync has completed. This way, we can avoid emitting incoming\n // call events if we get both the invite and answer/hangup in the same sync.\n // This happens quite often, eg. replaying sync from storage, catchup sync\n // after loading and after we've been offline for a bit.\n this.callEventBuffer = [];\n this.candidateEventsByCall = new Map<string, Array<MatrixEvent>>();\n }\n\n public start() {\n this.client.on(\"sync\", this.evaluateEventBuffer);\n this.client.on(\"Room.timeline\", this.onRoomTimeline);\n }\n\n public stop() {\n this.client.removeListener(\"sync\", this.evaluateEventBuffer);\n this.client.removeListener(\"Room.timeline\", this.onRoomTimeline);\n }\n\n private evaluateEventBuffer = async () => {\n if (this.client.getSyncState() === \"SYNCING\") {\n await Promise.all(this.callEventBuffer.map(event => {\n this.client.decryptEventIfNeeded(event);\n }));\n\n const ignoreCallIds = new Set<String>();\n // inspect the buffer and mark all calls which have been answered\n // or hung up before passing them to the call event handler.\n for (const ev of this.callEventBuffer) {\n if (ev.getType() === EventType.CallAnswer ||\n ev.getType() === EventType.CallHangup) {\n ignoreCallIds.add(ev.getContent().call_id);\n }\n }\n // now loop through the buffer chronologically and inject them\n for (const e of this.callEventBuffer) {\n if (\n e.getType() === EventType.CallInvite &&\n ignoreCallIds.has(e.getContent().call_id)\n ) {\n // This call has previously been answered or hung up: ignore it\n continue;\n }\n try {\n this.handleCallEvent(e);\n } catch (e) {\n logger.error(\"Caught exception handling call event\", e);\n }\n }\n this.callEventBuffer = [];\n }\n };\n\n private onRoomTimeline = (event: MatrixEvent) => {\n this.client.decryptEventIfNeeded(event);\n // any call events or ones that might be once they're decrypted\n if (this.eventIsACall(event) || event.isBeingDecrypted()) {\n // queue up for processing once all events from this sync have been\n // processed (see above).\n this.callEventBuffer.push(event);\n }\n\n if (event.isBeingDecrypted() || event.isDecryptionFailure()) {\n // add an event listener for once the event is decrypted.\n event.once(\"Event.decrypted\", () => {\n if (!this.eventIsACall(event)) return;\n\n if (this.callEventBuffer.includes(event)) {\n // we were waiting for that event to decrypt, so recheck the buffer\n this.evaluateEventBuffer();\n } else {\n // This one wasn't buffered so just run the event handler for it\n // straight away\n try {\n this.hLine truncated
|
||||
"// allow non-camelcase as these are events type that go onto the wire\n/* eslint-disable camelcase */\n\n// TODO: Change to \"sdp_stream_metadata\" when MSC3077 is merged\nexport const SDPStreamMetadataKey = \"org.matrix.msc3077.sdp_stream_metadata\";\n\nexport enum SDPStreamMetadataPurpose {\n Usermedia = \"m.usermedia\",\n Screenshare = \"m.screenshare\",\n}\n\nexport interface SDPStreamMetadataObject {\n purpose: SDPStreamMetadataPurpose;\n audio_muted: boolean;\n video_muted: boolean;\n}\n\nexport interface SDPStreamMetadata {\n [key: string]: SDPStreamMetadataObject;\n}\n\ninterface CallOfferAnswer {\n type: string;\n sdp: string;\n}\n\nexport interface CallCapabilities {\n 'm.call.transferee': boolean;\n 'm.call.dtmf': boolean;\n}\n\nexport interface CallReplacesTarget {\n id: string;\n display_name: string;\n avatar_url: string;\n}\n\nexport interface MCallAnswer {\n answer: CallOfferAnswer;\n capabilities: CallCapabilities;\n [SDPStreamMetadataKey]: SDPStreamMetadata;\n}\n\nexport interface MCallOfferNegotiate {\n offer: CallOfferAnswer;\n description: CallOfferAnswer;\n lifetime: number;\n capabilities: CallCapabilities;\n invitee?: string;\n [SDPStreamMetadataKey]: SDPStreamMetadata;\n}\n\nexport interface MCallSDPStreamMetadataChanged {\n [SDPStreamMetadataKey]: SDPStreamMetadata;\n}\n\nexport interface MCallReplacesEvent {\n replacement_id: string;\n target_user: CallReplacesTarget;\n create_call: string;\n await_call: string;\n target_room: string;\n}\n/* eslint-enable camelcase */\n",
|
||||
"/*\nCopyright 2021 Šimon Brandner <simon.bra.ag@gmail.com>\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport EventEmitter from \"events\";\nimport { SDPStreamMetadataPurpose } from \"./callEventTypes\";\nimport { MatrixClient } from \"../client\";\nimport { RoomMember } from \"../models/room-member\";\n\nexport enum CallFeedEvent {\n NewStream = \"new_stream\",\n MuteStateChanged = \"mute_state_changed\"\n}\n\nexport class CallFeed extends EventEmitter {\n constructor(\n public stream: MediaStream,\n public userId: string,\n public purpose: SDPStreamMetadataPurpose,\n private client: MatrixClient,\n private roomId: string,\n private audioMuted: boolean,\n private videoMuted: boolean,\n ) {\n super();\n }\n\n /**\n * Returns callRoom member\n * @returns member of the callRoom\n */\n public getMember(): RoomMember {\n const callRoom = this.client.getRoom(this.roomId);\n return callRoom.getMember(this.userId);\n }\n\n /**\n * Returns true if CallFeed is local, otherwise returns false\n * @returns {boolean} is local?\n */\n public isLocal(): boolean {\n return this.userId === this.client.getUserId();\n }\n\n /**\n * Returns true if audio is muted or if there are no audio\n * tracks, otherwise returns false\n * @returns {boolean} is audio muted?\n */\n public isAudioMuted(): boolean {\n return this.stream.getAudioTracks().length === 0 || this.audioMuted;\n }\n\n /**\n * Returns true video is muted or if there are no video\n * tracks, otherwise returns false\n * @returns {boolean} is video muted?\n */\n public isVideoMuted(): boolean {\n // We assume only one video track\n return this.stream.getVideoTracks().length === 0 || this.videoMuted;\n }\n\n /**\n * Replaces the current MediaStream with a new one.\n * This method should be only used by MatrixCall.\n * @param newStream new stream with which to replace the current one\n */\n public setNewStream(newStream: MediaStream) {\n this.stream = newStream;\n this.emit(CallFeedEvent.NewStream, this.stream);\n }\n\n public setAudioMuted(muted: boolean): void {\n this.audioMuted = muted;\n this.emit(CallFeedEvent.MuteStateChanged, this.audioMuted, this.videoMuted);\n }\n\n public setVideoMuted(muted: boolean): void {\n this.videoMuted = muted;\n this.emit(CallFeedEvent.MuteStateChanged, this.audioMuted, this.videoMuted);\n }\n}\n"
|
||||
"/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module.\n * @module utils\n */\n\nimport unhomoglyph from \"unhomoglyph\";\nimport promiseRetry from \"p-retry\";\nimport type NodeCrypto from \"crypto\";\n\n/**\n * Encode a dictionary of query parameters.\n * @param {Object} params A dict of key/values to encode e.g.\n * {\"foo\": \"bar\", \"baz\": \"taz\"}\n * @return {string} The encoded string e.g. foo=bar&baz=taz\n */\nexport function encodeParams(params: Record<string, string>): string {\n return new URLSearchParams(params).toString();\n}\n\nexport type QueryDict = Record<string, string | string[]>;\n\n/**\n * Decode a query string in `application/x-www-form-urlencoded` format.\n * @param {string} query A query string to decode e.g.\n * foo=bar&via=server1&server2\n * @return {Object} The decoded object, if any keys occurred multiple times\n * then the value will be an array of strings, else it will be an array.\n * This behaviour matches Node's qs.parse but is built on URLSearchParams\n * for native web compatibility\n */\nexport function decodeParams(query: string): QueryDict {\n const o: QueryDict = {};\n const params = new URLSearchParams(query);\n for (const key of params.keys()) {\n const val = params.getAll(key);\n o[key] = val.length === 1 ? val[0] : val;\n }\n return o;\n}\n\n/**\n * Encodes a URI according to a set of template variables. Variables will be\n * passed through encodeURIComponent.\n * @param {string} pathTemplate The path with template variables e.g. '/foo/$bar'.\n * @param {Object} variables The key/value pairs to replace the template\n * variables with. E.g. { \"$bar\": \"baz\" }.\n * @return {string} The result of replacing all template variables e.g. '/foo/baz'.\n */\nexport function encodeUri(pathTemplate: string,\n variables: Record<string, string>): string {\n for (const key in variables) {\n if (!variables.hasOwnProperty(key)) {\n continue;\n }\n pathTemplate = pathTemplate.replace(\n key, encodeURIComponent(variables[key]),\n );\n }\n return pathTemplate;\n}\n\n/**\n * The removeElement() method removes the first element in the array that\n * satisfies (returns true) the provided testing function.\n * @param {Array} array The array.\n * @param {Function} fn Function to execute on each value in the array, with the\n * function signature <code>fn(element, index, array)</code>. Return true to\n * remove this element and break.\n * @param {boolean} reverse True to search in reverse order.\n * @return {boolean} True if an element was removed.\n */\nexport function removeElement<T>(\n array: T[],\n fn: (t: T, i?: number, a?: T[]) => boolean,\n reverse?: boolean,\n) {\n let i;\n let removed;\n if (reverse) {\n for (i = array.length - 1; i >= 0; i--) {\n if (fn(array[i], i, array)) {\n removed = array[i];\n array.splice(i, 1);\n return removed;\n }\n }\n } else {\n for (i = 0; i < array.length; i++) {\n if (fn(array[i], i, array)) {\n removed = array[i];\n array.splice(i, 1);\n return removed;\n }\n }\n }\n return false;\n}\n\n/**\n * Checks if the given thing is a function.\n * @param {*} value The thing to check.\n * @return {boolean} True if it is a function.\n */\nexport function isFunction(value: any) {\n return Object.prototype.toString.call(value) === \"[object Function]\";\n}\n\n/**\n * Checks that the given object has the specified keys.\n * @param {Object} obj The object to check.\n * @param {string[]} keys The list of keys that 'obj' must have.\n * @throws If the object is missing keys.\n */\n// note using 'keys' here would shadow the 'keys' function defined above\nexport function checkObjectHasKeys(obj: object, keys: string[]) {\n for (let i = 0; i < keys.length; i++) {\n if (!obj.hasOwnProperty(keys[i])) {\n throw new Error(\"Missing required key: \" + keys[i]);\n }\n }\n}\n\n/**\n * Checks that the given object has no extra keys other than the specified ones.\n * @param {Object} obj The object to check.\n * @param {string[]} allowedKeys The list of allowed key names.\n * @throws If there are extra keys.\n */\nexport function checkObjectHasNoAddLine truncated
|
||||
"/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 New Vector Ltd\nCopyright 2019, 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link createNewMatrixCall} for the public API.\n * @module webrtc/call\n */\n\nimport { logger } from '../logger';\nimport { EventEmitter } from 'events';\nimport * as utils from '../utils';\nimport { MatrixEvent } from '../models/event';\nimport { EventType } from '../@types/event';\nimport { RoomMember } from '../models/room-member';\nimport { randomString } from '../randomstring';\nimport {\n MCallReplacesEvent,\n MCallAnswer,\n MCallInviteNegotiate,\n CallCapabilities,\n SDPStreamMetadataPurpose,\n SDPStreamMetadata,\n SDPStreamMetadataKey,\n MCallSDPStreamMetadataChanged,\n MCallSelectAnswer,\n MCAllAssertedIdentity,\n MCallCandidates,\n MCallBase,\n MCallHangupReject,\n} from './callEventTypes';\nimport { CallFeed } from './callFeed';\nimport { MatrixClient } from \"../client\";\nimport { ISendEventResponse } from \"../@types/requests\";\n\n// events: hangup, error(err), replaced(call), state(state, oldState)\n\n/**\n * Fires whenever an error occurs when call.js encounters an issue with setting up the call.\n * <p>\n * The error given will have a code equal to either `MatrixCall.ERR_LOCAL_OFFER_FAILED` or\n * `MatrixCall.ERR_NO_USER_MEDIA`. `ERR_LOCAL_OFFER_FAILED` is emitted when the local client\n * fails to create an offer. `ERR_NO_USER_MEDIA` is emitted when the user has denied access\n * to their audio/video hardware.\n *\n * @event module:webrtc/call~MatrixCall#\"error\"\n * @param {Error} err The error raised by MatrixCall.\n * @example\n * matrixCall.on(\"error\", function(err){\n * console.error(err.code, err);\n * });\n */\n\ninterface CallOpts {\n roomId?: string;\n invitee?: string;\n client?: any; // Fix when client is TSified\n forceTURN?: boolean;\n turnServers?: Array<TurnServer>;\n}\n\ninterface TurnServer {\n urls: Array<string>;\n username?: string;\n password?: string;\n ttl?: number;\n}\n\ninterface AssertedIdentity {\n id: string;\n displayName: string;\n}\n\nexport enum CallState {\n Fledgling = 'fledgling',\n InviteSent = 'invite_sent',\n WaitLocalMedia = 'wait_local_media',\n CreateOffer = 'create_offer',\n CreateAnswer = 'create_answer',\n Connecting = 'connecting',\n Connected = 'connected',\n Ringing = 'ringing',\n Ended = 'ended',\n}\n\nexport enum CallType {\n Voice = 'voice',\n Video = 'video',\n}\n\nexport enum CallDirection {\n Inbound = 'inbound',\n Outbound = 'outbound',\n}\n\nexport enum CallParty {\n Local = 'local',\n Remote = 'remote',\n}\n\nexport enum CallEvent {\n Hangup = 'hangup',\n State = 'state',\n Error = 'error',\n Replaced = 'replaced',\n\n // The value of isLocalOnHold() has changed\n LocalHoldUnhold = 'local_hold_unhold',\n // The value of isRemoteOnHold() has changed\n RemoteHoldUnhold = 'remote_hold_unhold',\n // backwards compat alias for LocalHoldUnhold: remove in a major version bump\n HoldUnhold = 'hold_unhold',\n // Feeds have changed\n FeedsChanged = 'feeds_changed',\n\n AssertedIdentityChanged = 'asserted_identity_changed',\n}\n\nexport enum CallErrorCode {\n /** The user chose to end the call */\n UserHangup = 'user_hangup',\n\n /** An error code when the local client failed to create an offer. */\n LocalOfferFailed = 'local_offer_failed',\n /**\n * An error code when there is no local mic/camera to use. This may be because\n * the hardware isn't plugged in, or the user has explicitly denied access.\n */\n NoUserMedia = 'no_user_media',\n\n /**\n * Error code used when a call event failed to send\n * because unknown devices were present in the room\n */\n UnknownDevices = 'unknown_devices',\n\n /**\n * Error code used when we fail to send the invite\n * for some reason other than there being unknown devices\n */\n SendInvite = 'send_invite',\n\n /**\n * An answer could not be created\n */\n CreateAnswer = 'create_answer',\n\n /**\n * Error code used when we fail to send the answer\n * for some reason other than there being unknown devices\n */\n SendAnswer = 'send_answer',\n\n /**\n * The session description from the other side could not be set\n */\n SetRemoteDescripLine truncated
|
||||
"/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixEvent } from '../models/event';\nimport { logger } from '../logger';\nimport { createNewMatrixCall, MatrixCall, CallErrorCode, CallState, CallDirection } from './call';\nimport { EventType } from '../@types/event';\nimport { MatrixClient } from '../client';\nimport { MCallAnswer, MCallHangupReject } from \"./callEventTypes\";\n\n// Don't ring unless we'd be ringing for at least 3 seconds: the user needs some\n// time to press the 'accept' button\nconst RING_GRACE_PERIOD = 3000;\n\nexport class CallEventHandler {\n client: MatrixClient;\n calls: Map<string, MatrixCall>;\n callEventBuffer: MatrixEvent[];\n candidateEventsByCall: Map<string, Array<MatrixEvent>>;\n\n constructor(client: MatrixClient) {\n this.client = client;\n this.calls = new Map<string, MatrixCall>();\n // The sync code always emits one event at a time, so it will patiently\n // wait for us to finish processing a call invite before delivering the\n // next event, even if that next event is a hangup. We therefore accumulate\n // all our call events and then process them on the 'sync' event, ie.\n // each time a sync has completed. This way, we can avoid emitting incoming\n // call events if we get both the invite and answer/hangup in the same sync.\n // This happens quite often, eg. replaying sync from storage, catchup sync\n // after loading and after we've been offline for a bit.\n this.callEventBuffer = [];\n this.candidateEventsByCall = new Map<string, Array<MatrixEvent>>();\n }\n\n public start() {\n this.client.on(\"sync\", this.evaluateEventBuffer);\n this.client.on(\"Room.timeline\", this.onRoomTimeline);\n }\n\n public stop() {\n this.client.removeListener(\"sync\", this.evaluateEventBuffer);\n this.client.removeListener(\"Room.timeline\", this.onRoomTimeline);\n }\n\n private evaluateEventBuffer = async () => {\n if (this.client.getSyncState() === \"SYNCING\") {\n await Promise.all(this.callEventBuffer.map(event => {\n this.client.decryptEventIfNeeded(event);\n }));\n\n const ignoreCallIds = new Set<String>();\n // inspect the buffer and mark all calls which have been answered\n // or hung up before passing them to the call event handler.\n for (const ev of this.callEventBuffer) {\n if (ev.getType() === EventType.CallAnswer ||\n ev.getType() === EventType.CallHangup) {\n ignoreCallIds.add(ev.getContent().call_id);\n }\n }\n // now loop through the buffer chronologically and inject them\n for (const e of this.callEventBuffer) {\n if (\n e.getType() === EventType.CallInvite &&\n ignoreCallIds.has(e.getContent().call_id)\n ) {\n // This call has previously been answered or hung up: ignore it\n continue;\n }\n try {\n await this.handleCallEvent(e);\n } catch (e) {\n logger.error(\"Caught exception handling call event\", e);\n }\n }\n this.callEventBuffer = [];\n }\n };\n\n private onRoomTimeline = (event: MatrixEvent) => {\n this.client.decryptEventIfNeeded(event);\n // any call events or ones that might be once they're decrypted\n if (this.eventIsACall(event) || event.isBeingDecrypted()) {\n // queue up for processing once all events from this sync have been\n // processed (see above).\n this.callEventBuffer.push(event);\n }\n\n if (event.isBeingDecrypted() || event.isDecryptionFailure()) {\n // add an event listener for once the event is decrypted.\n event.once(\"Event.decrypted\", async () => {\n if (!this.eventIsACall(event)) return;\n\n if (this.callEventBuffer.includes(event)) {\n // we were waiting for that event to decrypt, so recheck the buffer\n this.evaluateEventBuffer();\n } else {\n // This one wasn't buffered so just run the event handler for it\n Line truncated
|
||||
"// allow non-camelcase as these are events type that go onto the wire\n/* eslint-disable camelcase */\n\nimport { CallErrorCode } from \"./call\";\n\n// TODO: Change to \"sdp_stream_metadata\" when MSC3077 is merged\nexport const SDPStreamMetadataKey = \"org.matrix.msc3077.sdp_stream_metadata\";\n\nexport enum SDPStreamMetadataPurpose {\n Usermedia = \"m.usermedia\",\n Screenshare = \"m.screenshare\",\n}\n\nexport interface SDPStreamMetadataObject {\n purpose: SDPStreamMetadataPurpose;\n audio_muted: boolean;\n video_muted: boolean;\n}\n\nexport interface SDPStreamMetadata {\n [key: string]: SDPStreamMetadataObject;\n}\n\nexport interface CallCapabilities {\n 'm.call.transferee': boolean;\n 'm.call.dtmf': boolean;\n}\n\nexport interface CallReplacesTarget {\n id: string;\n display_name: string;\n avatar_url: string;\n}\n\nexport interface MCallBase {\n call_id: string;\n version: string | number;\n party_id?: string;\n}\n\nexport interface MCallAnswer extends MCallBase {\n answer: RTCSessionDescription;\n capabilities?: CallCapabilities;\n [SDPStreamMetadataKey]: SDPStreamMetadata;\n}\n\nexport interface MCallSelectAnswer extends MCallBase {\n selected_party_id: string;\n}\n\nexport interface MCallInviteNegotiate extends MCallBase {\n offer: RTCSessionDescription;\n description: RTCSessionDescription;\n lifetime: number;\n capabilities?: CallCapabilities;\n invitee?: string;\n [SDPStreamMetadataKey]: SDPStreamMetadata;\n}\n\nexport interface MCallSDPStreamMetadataChanged extends MCallBase {\n [SDPStreamMetadataKey]: SDPStreamMetadata;\n}\n\nexport interface MCallReplacesEvent extends MCallBase {\n replacement_id: string;\n target_user: CallReplacesTarget;\n create_call: string;\n await_call: string;\n target_room: string;\n}\n\nexport interface MCAllAssertedIdentity extends MCallBase {\n asserted_identity: {\n id: string;\n display_name: string;\n avatar_url: string;\n };\n}\n\nexport interface MCallCandidates extends MCallBase {\n candidates: RTCIceCandidate[];\n}\n\nexport interface MCallHangupReject extends MCallBase {\n reason?: CallErrorCode;\n}\n\n/* eslint-enable camelcase */\n",
|
||||
"/*\nCopyright 2021 Šimon Brandner <simon.bra.ag@gmail.com>\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport EventEmitter from \"events\";\nimport { SDPStreamMetadataPurpose } from \"./callEventTypes\";\nimport { MatrixClient } from \"../client\";\nimport { RoomMember } from \"../models/room-member\";\n\nconst POLLING_INTERVAL = 250; // ms\nconst SPEAKING_THRESHOLD = -60; // dB\n\nexport enum CallFeedEvent {\n NewStream = \"new_stream\",\n MuteStateChanged = \"mute_state_changed\",\n VolumeChanged = \"volume_changed\",\n Speaking = \"speaking\",\n}\n\nexport class CallFeed extends EventEmitter {\n private measuringVolumeActivity = false;\n private audioContext: AudioContext;\n private analyser: AnalyserNode;\n private frequencyBinCount: Float32Array;\n private speakingThreshold = SPEAKING_THRESHOLD;\n private speaking = false;\n\n constructor(\n public stream: MediaStream,\n public userId: string,\n public purpose: SDPStreamMetadataPurpose,\n private client: MatrixClient,\n private roomId: string,\n private audioMuted: boolean,\n private videoMuted: boolean,\n ) {\n super();\n\n if (this.hasAudioTrack) {\n this.initVolumeMeasuring();\n }\n }\n\n private get hasAudioTrack(): boolean {\n return this.stream.getAudioTracks().length > 0;\n }\n\n private initVolumeMeasuring(): void {\n const AudioContext = window.AudioContext || window.webkitAudioContext;\n if (!this.hasAudioTrack || !AudioContext) return;\n\n this.audioContext = new AudioContext();\n\n this.analyser = this.audioContext.createAnalyser();\n this.analyser.fftSize = 512;\n this.analyser.smoothingTimeConstant = 0.1;\n\n const mediaStreamAudioSourceNode = this.audioContext.createMediaStreamSource(this.stream);\n mediaStreamAudioSourceNode.connect(this.analyser);\n\n this.frequencyBinCount = new Float32Array(this.analyser.frequencyBinCount);\n }\n\n /**\n * Returns callRoom member\n * @returns member of the callRoom\n */\n public getMember(): RoomMember {\n const callRoom = this.client.getRoom(this.roomId);\n return callRoom.getMember(this.userId);\n }\n\n /**\n * Returns true if CallFeed is local, otherwise returns false\n * @returns {boolean} is local?\n */\n public isLocal(): boolean {\n return this.userId === this.client.getUserId();\n }\n\n /**\n * Returns true if audio is muted or if there are no audio\n * tracks, otherwise returns false\n * @returns {boolean} is audio muted?\n */\n public isAudioMuted(): boolean {\n return this.stream.getAudioTracks().length === 0 || this.audioMuted;\n }\n\n /**\n * Returns true video is muted or if there are no video\n * tracks, otherwise returns false\n * @returns {boolean} is video muted?\n */\n public isVideoMuted(): boolean {\n // We assume only one video track\n return this.stream.getVideoTracks().length === 0 || this.videoMuted;\n }\n\n /**\n * Replaces the current MediaStream with a new one.\n * This method should be only used by MatrixCall.\n * @param newStream new stream with which to replace the current one\n */\n public setNewStream(newStream: MediaStream): void {\n this.stream = newStream;\n this.emit(CallFeedEvent.NewStream, this.stream);\n\n if (this.hasAudioTrack) {\n this.initVolumeMeasuring();\n } else {\n this.measureVolumeActivity(false);\n }\n }\n\n /**\n * Set feed's internal audio mute state\n * @param muted is the feed's audio muted?\n */\n public setAudioMuted(muted: boolean): void {\n this.audioMuted = muted;\n this.emit(CallFeedEvent.MuteStateChanged, this.audioMuted, this.videoMuted);\n }\n\n /**\n * Set feed's internal video mute state\n * @param muted is the feed's video muted?\n */\n public setVideoMuted(muted: boolean): void {\n this.videoMuted = muted;\n this.emit(CallFeedEvent.MuteStateChanged, this.audioMuted, this.videoMuted);\n }\n\n /**\n * Starts emitting volume_changed events where the emitter value is in decibels\n * @param enabled emit volume changes\n */\n public measureVolumeActivity(enabled: boolean): void {\n if (enabled) {\n if (!this.audioContext ||Line truncated
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user