-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmatrix-solid.js
1889 lines (1684 loc) · 73.9 KB
/
matrix-solid.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Gitter or Marix chat data to Solid Chat
import * as sdk from "matrix-js-sdk";// https://github.com/matrix-org/matrix-js-sdk
/*
The Matrix spec: https://spec.matrix.org/latest/#common-concepts
The client-server bit of the matrix spec: https://spec.matrix.org/v1.5/client-server-api
Documentation for the SDK we are using: https://matrix.org/docs/guides/usage-of-the-matrix-js-sdk
*/
import myCrypto from 'crypto'
import * as dotenv from 'dotenv'
import * as $rdf from 'rdflib'
import solidNamespace from "solid-namespace"
// import * as solidNamespace from 'solid-namespace'
import * as Gitter from 'node-gitter'
import { SolidNodeClient } from 'solid-node-client'
import * as readlineSync from 'readline-sync'
import * as readline from 'readline'
const matrixUserId = "@timblbot:matrix.org";
const baseUrl = "http://matrix.org"
const MATRIX_TO_GITTER_MAP = { '!AdIacJniSdsOmHkZjQ:snopyta.org': 'solid/chat' } // https://matrix.to/#/#solid_chat:gitter.im?utm_source=gitter
const MESSAGES_AT_A_TIME = 100 // 3000?
const THREAD_SEARCH_RANGE = 90
const THREAD_LOAD_RANGE= 90
const THREAD_SCAN_RANGE = 365
const THREAD_SEARCH_CLIP_DATE = '2022-12-01' // Don't bother trying to hook up threads past that
const MESSAGE_LOAD_CLIP = '2023-02-14' // Don't load anything before this
const MAX_SCROLLS = 100
dotenv.config()
const command = process.argv[2]
const targetRoomName = process.argv[3]
const userPodBase = process.argv[4]
const GITTER = false
const MATRIX = true
const numMessagesToShow = 20
let matrixClient = null
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
// completer: completer,
});
// const MATRIX_APP_ORIGIN = 'timbl.com' // or makybe a solidcommmunity pod
if (typeof crypto === 'undefined') {
var crypto = myCrypto
// console.log("gitter-solid local crypo", crypto)
global.crypto = myCrypto
} else {
// console.log("gitter-solid global crypo", crypto)
}
// console.log("gitter-solid crypo", crypto)
// see https://www.npmjs.com/package/node-g
let gitter, GITTER_TOKEN, MATRIX_PASSWORD
if (GITTER) {
GITTER_TOKEN = process.env.GITTER_TOKEN
}
if (MATRIX) {
MATRIX_PASSWORD = process.env.MATRIX_PASSWORD
}
const ns = solidNamespace($rdf)
if (!ns.wf) {
ns.wf = new $rdf.Namespace('http://www.w3.org/2005/01/wf/flow#') // @@ sheck why necessary
}
/// should share with this solid-ui/src/chat/messageTools.
/* Emoji in Unicode
See https://www.unicode.org/emoji/charts/full-emoji-modifiers.html
More specfic types -- https://schema.org/ReactAction
AgreeAction
DisagreeAction
DislikeAction @@
EndorseAction
LikeAction
WantAction @@
*/
const emojiMap = {}
emojiMap[ns.schema('AgreeAction')] = '👍️' // What about skin variations ??! @@ https://www.unicode.org/emoji/charts/full-emoji-modifiers.html
emojiMap[ns.schema('DisagreeAction')] = '👎'
emojiMap[ns.schema('EndorseAction')] = '⭐️'
emojiMap[ns.schema('LikeAction')] = '❤️'
export function emojiFromActionClass (action) {
return emojiMap[action] || null
}
export function ActionClassFromEmoji (emoji) {
for (const a in emojiMap) {
if (emojiMap[a] === emoji) {
console.log(` ActionClassFromEmoji success ${emoji} -> ${a}`)
return $rdf.sym(a.slice(1, -1)) // remove < >
}
}
console.log(' ActionClassFromEmoji fail ${emoji}' )
return null
}
///////////// MATRIX /////////////////
let roomList = []
function getAndSortRoomList() {
const roomList = matrixClient.getRooms();
// console.log(' getAndSortRoomList ' + show(roomList))
roomList.sort(function (a, b) {
// < 0 = a comes first (lower index) - we want high indexes = newer
var aMsg = a.timeline[a.timeline.length - 1];
if (!aMsg) {
return -1;
}
var bMsg = b.timeline[b.timeline.length - 1];
if (!bMsg) {
return 1;
}
if (aMsg.getTs() > bMsg.getTs()) {
return 1;
} else if (aMsg.getTs() < bMsg.getTs()) {
return -1;
}
return 0;
});
return roomList
}
function showRoom (room) {
var msg = room.timeline[room.timeline.length - 1];
var dateStr = "---";
if (msg) {
dateStr = new Date(msg.getTs()).toISOString().replace(/T/, " ").replace(/\..+/, "");
}
var myMembership = room.getMyMembership();
const star = myMembership ? '*' : ' '
var roomName = room.name
return `<${room.roomId}> "${roomName}" (${room.getJoinedMembers().length} members)${star} ${dateStr}`
}
function printRoomList() {
// console.log(CLEAR_CONSOLE);
console.log("Room List:");
for (const room of roomList) {
console.log(showRoom(room))
}
}
function short (x) {
if (x === null) return 'null'
if (!x || typeof x !== 'object') return '*';
if (x.length) return `[${x.length}]`;
return `{${Object.keys(x).length}}`;
}
function show (x) {
if (x === null || x === undefined) return ' - '
const typ = typeof x
switch (typ) {
case 'null':
case 'undefined': return 'x'
case 'string': return `"${x}"`
case 'boolean':
case 'number': return x.toString()
case 'object':
if (x.length) return '[' + x.slice(0, 3).map(show).join(', ') + ']'
return '{' + Object.keys(x).slice(0,3).map(k => ` ${k}: ${short(x[k])}`).join('; ') + '}'
default: return `Type ${typ} ??`
}
}
// individualChatFolder', 'privateChatFolder', 'publicChatFolder
function archiveBaseURIFromMatrixRoom (room, config) {
// console.log('archiveBaseURIFromMatrixRoom ' , config.publicChatFolder.uri)
return config.publicChatFolder.uri
}
/** Decide URI of solid chat chanel from properties of Matrix room
*
* @param room {Room} - like 'solid/chat'
* https://matrix.to/#/#solid_chat:gitter.im
*/
function chatChannelFromMatrixRoom (room, config) {
const regexp = /^.*:gitter\.im$/ ; // These matrix rooms are grandfathered to look like the gitter rooms
console.log('chatChannelFromMatrixRoom room: ' + showRoom(room))
let segment
if (MATRIX_TO_GITTER_MAP[room.roomId]) {
segment = MATRIX_TO_GITTER_MAP[room.roomId]
console.log('Mapped matrix gitter to solid as special case: ', segment)
} else if (room.roomId.endsWith('gitter.im')) {
if (room.name.match(/^[a-zA-Z0-9_-]*\/[a-zA-Z0-9_-]*/)) { // already as a/b
segment = room.name // like linkeddata/MasterCard_workshop
} else if (room.name.match(/^[a-zA-Z0-9-]*_[a-zA-Z_0-9-]*/)) { // a_b
segment = room.name.split('_').join('/')
console.log('Converted matrix gitter to solid as a/b: ', segment)
} else {
throw new Error(`Room ${room.roomId} be a gitterim but name ${room.name} not a/b form`)
}
} else if (room.name.match(/[a-zA-Z0-9]*\/[a-zA-Z0-9]*/)) {
} else {
const [ sigilled, host ] = room.roomId.split(':')
const name = sigilled.slice(1) // remove the '!' for the room
segment = host + '/' + encodeURIComponent(name)
}
const archiveBaseURI = archiveBaseURIFromMatrixRoom(room, config)
if (!archiveBaseURI.endsWith('/')) throw new Error('base should end with slash')
const path = archiveBaseURI + segment
const solidChannel = $rdf.sym(path + '/index.ttl#this')
console.log(` chatChannelFromMatrixRoom -> channel ${solidChannel}`)
return solidChannel
}
function userFromMatrixId (id, config) {
const peopleBaseURI = config.publicUserFolder.uri
return $rdf.sym(peopleBaseURI + encodeURIComponent(id) + '/index.ttl#this')
}
async function authorFromMatrix (userData, config) {
/* user state looks like
"avatar_url":"mxc://matrix.org/QGLfsOamRItelTTqJypDlicO",
"displayname":"Mal Burns",
"membership":"join"} <-- relationship to group join or invite (-ed)?
*/
async function saveMatrixUserData (userData, person, config) {
const doc = person.doc()
console.log(`Person "${userData.displayName}" pic <${userData.avatar_url}>`)
store.add(person, ns.rdf('type'), ns.vcard('Individual'), doc)
store.add(person, ns.rdf('type'), ns.foaf('Person'), doc)
store.add(person, ns.vcard('fn'), userData.displayName, doc)
if (userData.id.endsWith('gitter.im')) {
const nick = userData.id.split('-')[0] // @@ kludge 'therealimy-60b3548f6da03739847dbe51:gitter.im'
userData.nick = nick
const github = 'https://github.com/' + nick // @@ watch out for twitter based folks
store.add(person, ns.foaf('homepage'), github, doc) // @@ check
console.log(' Gitter homepage guess ', github)
}
store.add(person, ns.foaf('nick'), userData.nick, doc)
if (userData.avatar_url) {
const avatarHTTPUrl = matrixClient.mxcUrlToHttp(userData.avatar_url, null, null, null, true) // Don;t get thumbnail
console.log(' photo "mxc:..." convertd to ', avatarHTTPUrl)
store.add(person, ns.vcard('photo'), $rdf.sym(avatarHTTPUrl), doc)
}
toBePut[doc.uri] = true
}
const peopleBaseURI = config.publicUserFolder.uri
//var person = $rdf.sym(peopleBaseURI + encodeURIComponent(userData.id) + '/index.ttl#this') // @@ matrix-
const person = userFromMatrixId(userData.id, config)
console.log(` person id: ${userData.id} -> solid ${person}`)
if (peopleDone[person.uri]) {
console.log(' matrix person already saved: ' + person.uri)
return person
}
var doc = person.doc()
if (toBePut[doc.uri]) { // already have stuff to save -> no need to load
// console.log(' (already started to person file) ' + doc)
} else {
try {
console.log(' fetching person file: ' + doc)
await fetcher.load(doc, clone(normalOptions)) // If exists, fine... leave it
} catch (err) {
if (err.response && err.response.status && err.response.status === 404) {
console.log('No person file yet, creating ' + person)
await saveMatrixUserData(userData, person, config) // Patch the file into existence
peopleDone[person.uri] = true
return person
} else {
console.log(' #### Error reading person file ' + err)
console.log(' #### Error reading person file ' + JSON.stringify(err))
console.log(' err.response ' + err.response)
console.log(' err.response.status ' + err.response.status)
process.exit(8)
}
}
peopleDone[person.uri] = true
}
return person
}
/* Convert internal self-identifying Id into matrix: URI
See https://spec.matrix.org/v1.6/appendices/#matrix-uri-scheme
But see https://spec.matrix.org/v1.6/appendices/#common-identifier-format
for the sigils which also include '+'
URNs like matrix: URIs are generally less useful than HTTP URIs.
*/
function toMatrixThing (id) {
const map = {
'@': 'u',
'$': 'e',
'!': 'room',
'#': 'r'
}
if (!map[id[0]]) {
throw new Error('toMatrixThing: Unknown Matrix Sigil ' + id)
}
return 'matrix:///' + map[id[0]] + '/' + id.slice(1)
}
function deSigil (eventId) {
if (eventId === undefined) {
return undefined
}
if (eventId.startsWith('$')) {
return eventId.slice(1)
}
throw new Error('Matrix event is should hve had a $ ' + eventId)
}
async function saveUniqueValueToChannel (chatChannel, predicate, value, config) {
const prop = predicate.uri.split('#')[1]
await store.fetcher.load(chatChannel)
/*
const old = store.each(chatChannel, predicate, null, chatChannel.doc())
if (old.length === 1 && old[0].sameTerm(value)) {
console.log(` ( ${prop }unchanged)`)
} else {
for (const img of old) { // Matrix rooms only hae one avatar at a time
console.log(` removing old ${prop}: ${img}`)
store.remove(chatChannel, predicate, img, chatChannel.doc())
}*/
console.log(` Adding room state to channel ${prop}: ${value}`)
store.add(chatChannel, predicate, value, chatChannel.doc())
toBePut[chatChannel.doc().uri] = true
}
function timeOfEvent(event) {
return new Date(event.getTs()).toISOString().replace(/T/, " ").replace(/\..+/, "");
}
function getRichText (content) {
if (content.formatted_body) {
if (content.format !== 'org.matrix.custom.html') {
throw new Error(`Event rich message has format "${content.format}" expected "org.matrix.custom.html"`)
}
// console.log(' m.room.message contents: ', content)
return content.formatted_body
}
return undefined
}
/* Handle one Matrix Message
*/
async function handleMatrixMessage (event, room, chatChannel, config) {
const userData = {}
let sender = event.getSender() // like @timbl:matrix.org
if (sender.startsWith('@')) sender = sender.slice(1) // strip Sigil [sic]
// The matrix people add 'gitter-' prefix to a gitter ID when importing ito to matrix.
// e do NOT need to add when importing Matrix to Solid.
userData.id = sender // Matrix ID
userData.nick = sender.split(':')[0]
//console.log(' @@@ sender: ', sender)
const name = event.sender ? event.sender.name : event.getSender();
userData.name = name
userData.displayName = name
var time = new Date(event.getTs()).toISOString().replace(/T/, " ").replace(/\..+/, "");
var body = "";
const content = event.getContent()
userData.avatar_url = content.avatar_url
const eventType = event.getType()
const eventId = event.event.event_id
console.log('\n Event id ', eventId)
// MessageData: { text, richText, replyTo, threadRoot, target, isEmotion, replaces, metadata }
const messageData = { sender, time, id: eventId }
const isState = event.isState()
const flag = event.isState() ? 'S' : 'M'
console.log(`<< ${flag} [${time}] ${eventType} <${userData.id}> "${name}" ... ${eventId.slice(-10)}:-`)
if (event.event && event.event.redacted_because) {
console.log('> Note REDACTED event because:', event.event.redacted_because)
console.log(` Redacted event isState: ${isState}`)
messageData.text = '<redacted>' // fill
// Redacted events don'y have msgType
// return time
}
// Found a case where a thread rel was just misssung fomr the getContrnt() version
const relatesTo = content['m.relates_to'] || event.event.content['m.relates_to']
if (relatesTo) {
messageData.target = deSigil(relatesTo.event_id)
const relType = relatesTo.rel_type // m.annotation
if (relType === 'm.annotation') {
if (eventType !== 'm.reaction') {
throw new Error('Why do we have annotation but not on an reaction?')
} else {
}
} else if (relType === 'm.replace') { // https://spec.matrix.org/v1.6/client-server-api/#event-replacements
/* The original event must not, itself, have a rel_type of m.replace
(i.e. you cannot edit an edit — though you can send multiple edits for a single original event). */
console.log(' This REPLACES ' + messageData.target)
messageData.replaces = messageData.target
// @@@ code me .. replaces target -> dct:isReplacedBy
} else if (relType === 'm.thread') {
console.log(' This has thread ' + messageData.target)
messageData.threadRoot = messageData.target
} else {
if (relatesTo['m.in_reply_to']) {
messageData.replyTo = deSigil(relatesTo['m.in_reply_to'].event_id)
console.log(' Straight reply (no thread)' + messageData.replyTo)
} else {
console.log('Relationship with no rel_type or m.in_reply_to', relatesTo)
throw new Error ('Relationship with no rel_type or m.in_reply_to')
}
}
}
if (eventType === 'm.reaction') {
if (relatesTo) {
const emotion = relatesTo.key // Emoji
// @@ Add code to put the solid reaction in the chat file ... see the toolbar in solid chat
console.log(`Storing m.reaction ${emotion} to ${messageData.target} by ${sender}`)
const action = { reactionId: eventId, sender, time, target:messageData.target, content:emotion, senderId:sender }
await storeAction(action, config)
/* Should be saved like
<#id1678102306625> <http://schema.org/agent> <https://timbl.inrupt.net/profile/card#me>;
a <http://schema.org/AgreeAction>;
<http://schema.org/target> <#Msg1677678647433>.
*/
} else if (event.event && event.event.redacted_because){
console.log(' Redacted m.reaction ' + eventId)
} else {
console.log(' @reaction event we dont understand:, ', event)
throw new Error('@@ m.reaction content we dont understand - no relatdeTo')
}
// Like {"m.relates_to":{"event_id":"$167611182453162yhMpM:matrix.org","key":"👋","rel_type":"m.annotation"}}
/////////////////////////////////// State messages
} else if (event.isState()) {
console.log('State event')
// console.log('State event', event)
userData.avatar_url = content.avatar_url
if (content.avatar_url && content.avatar_url.startsWith('mxc:')) {
const avatarHTTPUrl = matrixClient.mxcUrlToHttp(content.avatar_url, null, null, null, true) // Don;t get thumbnail
console.log(' avatar mxc: converted to ', avatarHTTPUrl)
userData.avatar_url = avatarHTTPUrl
}
if (eventType === 'm.room.canonical_alias') {
const alias = toMatrixThing(content.alias)
await saveUniqueValueToChannel(chatChannel, ns.rdfs('comment'), `canonical alias: ${alias}.`, config) // Eg public
} else if (eventType === 'm.room.topic') {
await saveUniqueValueToChannel(chatChannel, ns.dct('title'), content.topic, config) // Eg public
} else if (eventType === 'm.room.history_visibility') {
await saveUniqueValueToChannel(chatChannel, ns.rdfs('comment'), `history_visibility: ${content.history_visibility}.`, config) // Eg public
} else if (eventType === 'm.room.encryption') {
await saveUniqueValueToChannel(chatChannel, ns.rdfs('comment'), `Encryption: algorithm: ${content.algorithm}.`, config) // eg 'm.megolm.v1.aes-sha2'
} else if (eventType === 'm.room.guest_access') {
await saveUniqueValueToChannel(chatChannel, ns.rdfs('comment'), `Guest_access: ${content.guest_access}.`, config) // Eg can_join
} else if (eventType === 'm.room.join_rules') {
await saveUniqueValueToChannel(chatChannel, ns.rdfs('comment'), `Join rules: ${content.join_rules}.`, config) // Eg public
} else if (eventType === 'm.room.create') {
if (content.origin_server_ts) {
const created = new Date(0 + content.origin_server_ts)
console.log(` Room creation date "${content.origin_server_ts}" -> ${created}`)
await saveUniqueValueToChannel(chatChannel, ns.dct('created'), created, config)
}
const creator = toMatrixThing(content.creator)
await saveUniqueValueToChannel(chatChannel, ns.dct('creator'), creator, config)
if (content.room_version) {
await saveUniqueValueToChannel(chatChannel, ns.rdfs('comment'), `Room version: ${content.room_version}`, config)
}
} else if (eventType === 'm.room.member') {
const solidPerson = await authorFromMatrix(userData, config)
console.log('State: updated ' + solidPerson + ': ', userData)
console.log('State m.room.member all actions should be done.')
} else if (eventType == 'm.room.name') {
if (!content.name) throw new Error(' Missing room name:', event)
await saveUniqueValueToChannel(chatChannel, ns.vcard('fn'), content.name, config)
} else if (eventType === 'm.room.avatar') {
console.log('@@ State m.room.avatar: ' , event)
if (!content.url) throw new Error(' Missing room avatar:', event)
const rawAvatar = content.url
const avatarURL = matrixClient.mxcUrlToHttp(rawAvatar, null, null, null, true)
const avatar = $rdf.sym(avatarURL)
const roomId = event.event.room_id
await saveUniqueValueToChannel(chatChannel, ns.vcard('photo'), avatar, config)
} else if (eventType === 'im.gitter.project_association') {
// A gitter extension to link to github
if (content.type === 'GH_ORG') {
// like externalId: null, linkPath: 'rdfjs', platform: 'github.com', type: 'GH_ORG'
const repoURI = `https://${content.platform}/${content.linkPath}/`
console.log(` Got related Githb Organization ${repoURI} 👍`)
await saveUniqueValueToChannel(chatChannel, ns.foaf('homepage'), $rdf.sym(repoURI), config)
} else if (content.type === 'GH_REPO') {
// like: { externalId: '58017436', linkPath: 'solid/mashlib', platform: 'github.com',type: 'GH_REPO'},
const repoURI = `https://${content.platform}/${content.linkPath}/`
console.log(` Got related Githb repo ${repoURI} 👍`)
await saveUniqueValueToChannel(chatChannel, ns.doap('repository'), $rdf.sym(repoURI), config)
} else if (content.type === 'GL_PROJECT') {
const repoURI = `https://${content.platform}/${content.linkPath}/`
await saveUniqueValueToChannel(chatChannel, ns.foaf('homepage'), $rdf.sym(repoURI), config)
// externalId: '7527683', linkPath: 'gitlab-org/gitter/node-gitter', platform: 'gitlab.com', type: 'GL_PROJECT'
} else {
console.log('@@ Dont understand project_association content', content)
throw new Error('Gitter project_association has unnown type: ' + content.type)
}
} else if (eventType === 'org.matrix.msc3946.room_predecessor' || eventType === 'org.matrix.room_predecessor') {
if (!content.predecessor_room_id) throw new Error('predecessor_room_id with no predecessor_room_id')
await saveUniqueValueToChannel(chatChannel, ns.schema('successorOf'), toMatrixThing(content.predecessor_room_id), config) // @@ better pred?
} else if (eventType === 'm.room.power_levels') {
// For this room, what user power level is needed for actions and event types?
// https://spec.matrix.org/v1.6/client-server-api/#mroompower_levels
console.warn('Inoring state power levels', content) // useful to store in the room
} else if (eventType === 'm.room.bot.options') { // { github: { default_repo: 'linkeddata/dokieli' } }
if (content.github && content.github.default_repo) {
await saveUniqueValueToChannel(chatChannel, ns.doap('repository'), $rdf.sym('https://github.com/' + content.github.default_repo + '/'), config)
}
} else if (eventType === 'm.space.child') {
// like suggested: false, via: [ 'gitter.im', 'matrix.org', 'chat.semantic.works' ]
console.log('Ignoring event type ' + eventType)
} else if (eventType === 'uk.half-shot.bridge') {
console.log('Ignoring event type ' + eventType)
} else { // eg also im.vector.modular.widgets
console.log('State type ' + eventType + ' unknown: content: ', content)
console.warn('State type ' + eventType + ' unknown: event: ', event)
// throw new Error('State type unknown: ' + eventType)
}
} else { // NOT STATE
if (eventType === 'm.room.encrypted') {
console.log('Warning: encrypted messages are not supported.')
messageData.text = content.ciphertext.slice(0,60) + '...'
} else if (eventType === "m.room.redaction") {
console.log(' Ignoring REDACTED: ' + event.event.redacts)
messageData.text = '<redaction>'
} else if (eventType === "m.room.message") {
if (event.event && event.event.redacted_because) {
messageData.text = '' // Redacted message and redacting message are both hidden
messageData.deleted = true
// https://spec.matrix.org/v1.2/client-server-api/#mroommessage-msgtypes
} else if (content.msgtype === 'm.emote') {
console.log(' Hey -- emote', content)
messageData.text = content.body
messageData.richText = getRichText(content)
messageData.isEmotion = true
} else if (content.msgtype === 'm.audio' || content.msgtype === 'm.file' || content.msgtype === 'm.video') {
// body: 'foo.ttl',
// info: { mimetype: 'text/turtle', size: 10 }
messageData.metadata = content.info // mimetype etc
messageData.text = matrixClient.mxcUrlToHttp(content.url, null, null, null, true)
console.log(' File url', messageData.text)
} else if (content.msgtype === 'm.image') {
// body: 'image.png',
// info: { h: 256, mimetype: 'image/png', size: 15119, w: 256,
// 'xyz.amorgan.blurhash': 'UBHxOUxt00Icxea#j;j@00Rl_5xns=j@R#j?'},
messageData.metadata = content.info // mimetype etc
messageData.text = matrixClient.mxcUrlToHttp(content.url, null, null, null, true)
console.log('@@ Image body content', content)
console.log('@@ Image url', messageData.text)
} else if (content.msgtype === 'm.text' || content.msgtype === 'm.notice') {
messageData.text = content.body
messageData.richText = getRichText(content)
} else {
if (!content.msgtype) { // no mssage type given at all?
messageData.text = '<untyped>'
if (event.unsigned && event.unsigned.redacted_because) {
messageData.text = '<redacted>'
}
} else {
console.log(` @@ checkout this ${content.msgtype} content`, content)
console.log(` @@ checkout this ${content.msgtype} event`, event)
// throw new Error(`Event m.message has unexpected message type "${content.msgtype}"`)
}
}
}
const gitterMessage = { id: eventId.slice(1), sent: messageData.time, fromUser: messageData.sender, text: messageData.text,
replaces: messageData.replaces, replyTo: messageData.replyTo, threadRoot: messageData.threadRoot, isEmotion: messageData.isEmotion, metadata: messageData.metadata }
const archiveBaseURI = archiveBaseURIFromMatrixRoom(room, config)
const author = await authorFromMatrix(userData, config)
if (typeof messageData.text !== 'string') {
console.log('No text ' + messageData.text + ' on event: ', event)
throw new Error(`Matrix message: No main text in message ${eventId}`)
}
await storeMessage (chatChannel, gitterMessage, archiveBaseURI, author)
}
console.log(`${flag} >>>> [${time}] ${eventType} <${userData.id}> "${name}": ${body.slice(0,80)}`)
return time
}
async function loadRoomMessages (room, config) {
async function getSome () {
var result
for (var chunk = 0; chunk < MAX_SCROLLS; chunk++) {
console.log('Scrollback:')
result = await matrixClient.scrollback(room, MESSAGES_AT_A_TIME);
console.log(' Result of scrollback ' + show(result)) // show(result)
// console.log(` oldState `, result.oldState)
console.log(` paginationToken ${result.oldState.paginationToken}`)
const timeline = result.timeline
const n = timeline.length
console.log(` (${n}) from ${timeOfEvent(timeline[0])} to ${timeOfEvent(timeline[n-1])} `)
const earliestDate = timeOfEvent(timeline[0])
if (earliestDate < MESSAGE_LOAD_CLIP) {
console.log(` Found message ${earliestDate} before ${MESSAGE_LOAD_CLIP} ✅`)
break
}
}
return result
}
console.log(`loadRoomMessages: room name ${room.name}`)
const chatChannel = chatChannelFromMatrixRoom(room, config) // console.log(show(room))
const result = await getSome()
var earliestMessage = null
var latestMessage = null
var events = 0
var messages = 0
const eventTypes = {}
const timeline = result.timeline;
for (var i = 0; i < timeline.length; i++) {
const item = timeline[i]
const event = item.event
events += 1
const time = await handleMatrixMessage(item, room, chatChannel, config);
if (!earliestMessage || time < earliestMessage) earliestMessage = time;
if (!latestMessage || time > latestMessage) latestMessage = time;
}
console.log()
console.log(`Room name ${room.name}`)
console.log(' Events ', events)
console.log(' Messages ', messages)
console.log(' Earliest message ', earliestMessage)
console.log(' Latest message ', latestMessage)
console.log(' toBeLinked length ' + toBeLinked.length)
console.log(' editedMessages length ' + Object.keys(editedMessages).length)
console.log(' toBeExecuted length ' + toBeExecuted.length)
for (let [originalId, edited] of Object.entries(editedMessages)) {
console.log(` editedMessages: ${originalId} -> message ${edited}`)
const originalURI = eventMap[originalId]
let original = null
if (!originalURI) {
// throw new Error(' editedMessages: Cant find original ' + originalId)
console.warn(' editedMessages: Cant find original ' + originalId)
} else {
original = $rdf.sym(originalURI)
console.log(` editedMessages: original ${original}`)
edited.push(original) // might as well just sort it with the others
}
const sortMe = edited.map(message => [store.any(message, ns.dct('created'), null, message.doc()), message])
sortMe.sort()
console.log('editedMessages : all messsages ' + sortMe.length)
if (sortMe.length > 1) {
console.log(`editedMessages for ${original}: ` + sortMe.map(x => ` time ${x[0]} message ${x[1].uri.slice(-10)}`).join('\n '))
}
const timeley = sortMe.filter(x => x[0] && x[0].value > MESSAGE_LOAD_CLIP)
console.log('editedMessages : timeley messsages ' + timeley.length)
for (let i = 0; i < timeley.length - 1; i++) { // All but one
const earlier = timeley[i][1]
const later = timeley[i+1][1]
console.log(` editedmessages finally ${earlier.uri.slice(-10)} replaced by ${later.uri.slice(-10)} `)
store.add(earlier, ns.dct('isReplacedBy'), later, earlier.doc())
toBePut[earlier.doc().uri] = true
if (!earlier.doc().sameTerm(later.doc())) {
store.add(earlier, ns.dct('isReplacedBy'), later, later.doc())
toBePut[later.doc().uri] = true
}
}
}
if (toBeLinked.length > 0) {
await linkEverything()
}
await executeEverything()
console.log(' toBePut length ' + Object.keys(toBePut).length)
await saveEverythingBack()
}
async function linkEverything () {
console.log('linkEverything: toBeLinked length ' + toBeLinked.length)
let successes = 0, failures = 0;
while(toBeLinked.length > 0) {
const { message, predicate, target, reverse } = toBeLinked.pop()
const targetMessageURI = eventMap[target]
// const targetMessage = await findEventById(message, target)
if (!targetMessageURI) {
console.warn(` linkEverything: Failed to find ${target} around ${message} ❌`)
// throw new Error (`linkEverything: Failed to find ${target} near ${message}`)
failures += 1
} else {
successes += 1
const targetMessage = $rdf.sym(targetMessageURI)
// console.log(` Found ${target} at ${targetMessage} ✅`)
if (message.doc().sameTerm(targetMessage.doc())) {
console.log(`(Found ${targetMessage} in same doc as ${message}) `)
}
if (!reverse) {
store.add(message, predicate, targetMessage, message.doc())
store.add(message, predicate, targetMessage, targetMessage.doc())
} else {
store.add(targetMessage, predicate, message, message.doc())
store.add(targetMessage, predicate, message, targetMessage.doc())
}
toBePut[message.doc().uri] = true
toBePut[targetMessage.doc().uri] = true
}
}
console.log(` linkEverything: ${successes} successes, ${failures} failures.`)
}
async function executeEverything () {
console.log('execureEverything: number toBeExecuted: ' + toBeExecuted.length)
while(toBeExecuted.length > 0) {
// console.log('Executing one:')
toBeExecuted.pop()()
}
}
async function processMatrixRoom (room, config) {
console.log(`\n Room ${showRoom(room)}`)
if (command === 'catchup') {
newMessages = 0
oldMessages = 0
const already = await initializeChannel(room, config)
var myMembership = room.getMyMembership();
await loadRoomMessages(room, config)
console.log(`Totals for room ${room.roomId} old messages: ${oldMessages}, new: ${newMessages}`)
} else if (command === 'show') {
const chatChannel = chatChannelFromMatrixRoom(room, config)
await store.fetcher.load(chatChannel.doc())
const sts = store.connectedStatements(chatChannel)
const text = $rdf.serialize(chatChannel.doc(), store, chatChannel.doc().uri, 'text/turtle')
console.log('Channel data:' + text)
} else if (command === 'init') {
const chatChannel = chatChannelFromMatrixRoom(room, config)
await initializeChannel(room, config)
await saveEverythingBack()
console.log('Initialised ' + chatChannel)
} else if (command === 'list') {
showRoom(room)
} else {
console.log('Unknown command. Commands are :list, int, catchup' )
}
}
async function processMatrixRooms (config) {
console.log(`We see ${roomList.length} Matrix rooms`)
if (targetRoomName === 'all') {
for (let i = 0; i < roomList.length; i++) {
const room = roomList[i]
await processMatrixRoom(room, config)
}
} else {
for (let i = 0; i < roomList.length; i++) {
const room = roomList[i]
if (targetRoomName === room.name) {
console.log(` Found room <${room.roomId}> as name "${targetRoomName}"`)
await processMatrixRoom(room, config)
return;
} else if (targetRoomName === room.roomId) {
console.log(` Found room <${room.roomId}> as id "${targetRoomName}"`)
await processMatrixRoom(room, config)
return;
}
}
console.error(`Error: Target rooom name ${targetRoomName} not found.\nRooms:`)
printRoomList()
}
console.log('All done, exiting.')
process.exit(0)
}
async function initialiseMatrix(config) {
matrixClient = sdk.createClient({ baseUrl: "https://matrix.org/"});
const response = await matrixClient.login("m.login.password", {"user": "timblbot", "password": MATRIX_PASSWORD})
console.log(' login returned', response);
console.log(' New matrix client with base ', baseUrl)
// const response = matrixClient.login("m.login.password", {"user": "timblbot", "password": MATRIX_PASSWORD})
const accessToken = response.access_token
// if (!accessToken) throw new Error('No access token from matrix')
// .then((response) => { console.log(response.access_token);});
const client = matrixClient
await client.startClient({ initialSyncLimit: 10 });
client.once("sync", async function (state, prevState, res) {
if (state === "PREPARED") {
console.log("prepared");
await processMatrixRooms(config)
console.log(` to be put back: ${Object.keys(toBePut).length}`)
await saveEverythingBack()
// console.log(` should be all put back: ${Object.keys(toBePut).length}`)
console.log('Exit.')
process.exit(0)
} else {
console.log('Fatal Error: state not prepared: ' + state);
// console.log(state);
process.exit(1);
}
});
matrixClient.startClient(numMessagesToShow); // messages for each room.
roomList = matrixClient.getRooms();
console.log('getRooms ' + JSON.stringify(roomList)) //
matrixClient.on("Room", function () {
roomList = getAndSortRoomList();
// console.log('on Room room list: ' + roomList.length + ' rooms')
});
}
////////////////////////////////////// End of matrix
async function init() {
if(!command) {
command = await readlineSync.question('Command (e.g. create) : ');
}
if(!targetRoomName) {
targetRoomName = await readlineSync.question('Gitter Room (e.g. solid/chat) : ');
}
if (GITTER) {
if (!GITTER_TOKEN) {
GITTER_TOKEN = await readlineSync.question('Gitter Token : ');
}
gitter = new Gitter(GITTER_TOKEN)
}
if (MATRIX) {
const config = await(loadConfig())
await initialiseMatrix(config)
}
}
async function confirm (q) {
while (1) {
var a = (await readlineSync.question(q+' (y/n)? ')).trim().toLowerCase();
if (a === 'yes' || a === 'y') return true
if (a === 'no' || a === 'n') return false
console.log(' Please reply y or n')
}
}
const normalOptions = {
// headers: {Authorization: 'Bearer ' + SOLID_TOKEN}
}
const forcingOptions = {
// headers: {Authorization: 'Bearer ' + SOLID_TOKEN},
force: true }
function clone (options) {
return Object.assign({}, options)
}
/// ///////////////////////////// Solid Bits
const auth = new SolidNodeClient({parser:$rdf})
const fetcherOpts = {fetch: auth.fetch.bind(auth), timeout: 900000};
const store = $rdf.graph()
const kb = store // shorthand -- knowledge base
const fetcher = $rdf.fetcher(kb, fetcherOpts)
const updater = new $rdf.UpdateManager(kb)
function delayMs (ms) {
console.log('pause ... ')
return new Promise(resolve => setTimeout(resolve, ms))
}
function chatDocumentFromDate (chatChannel, date) {
let isoDate = date.toISOString() // Like "2018-05-07T17:42:46.576Z"
var path = isoDate.split('T')[0].replace(/-/g, '/') // Like "2018/05/07"
path = chatChannel.dir().uri + path + '/chat.ttl'
return $rdf.sym(path)
}
// individualChatFolder', 'privateChatFolder', 'publicChatFolder
function archiveBaseURIFromGitterRoom (room, config) {
// const folder = room.oneToOne ? config.individualChatFolder
// : room.public ? config.publicChatFolder : config.privateChatFolder
// return (folder.uri) ? folder.uri : folder // needed if config newly created
return config.publicChatFolder // @@ Those are the only things we are really wit ATM but change later!!!
}
/** Decide URI of solid chat chanel from properties of gitter room
*
* @param room {Room} - like 'solid/chat'
*/
function chatChannelFromGitterRoom (room, config) {
var path
let segment = room.name.split('/').map(encodeURIComponent).join('/') // Preseeve the slash begween org and room
if (room.githubType === 'ORG') {
segment += '/_Organization' // make all multi rooms two level names
}
var archiveBaseURI = archiveBaseURIFromGitterRoom(room, config)
if (!archiveBaseURI.endsWith('/')) throw new Error('base should end with slash')
if (room.oneToOne) {
var username = room.user.username
if (!username) throw new Error('one-one must have user username!')
console.log(` ${room.githubType}: ${username}: ${room.name}`)
path = archiveBaseURI + username
} else {
path = archiveBaseURI + segment
}
return $rdf.sym(path + '/index.ttl#this')
}
/** Track gitter users
*/
async function putResource (doc) {
delete fetcher.requested[doc.uri] // invalidate read cache @@ should be done by fetcher in future
return fetcher.putBack(doc, clone(normalOptions))
}
async function loadIfExists (doc) {
try {
// delete fetcher.requested[doc.uri]
await fetcher.load(doc, clone(normalOptions))
return true
} catch (err) {
if (err.response && err.response.status && err.response.status === 404) {
// console.log(' No chat file yet, creating later ' + doc)
return false
} else {
console.log(' #### Error reading file ' + err)
console.log(' error object ' + JSON.stringify(err))
console.log(' err.response ' + err.response)
console.log(' err.response.status ' + err.response.status)
process.exit(4)
}
}
return false
}
function suitable (x) {
let tail = x.uri.slice(0, -1).split('/').slice(-1)[0]
if (!'0123456789'.includes(tail[0])) return false // not numeric
return true
// return kb.anyValue(chatDocument, POSIX('size')) !== 0 // empty file?
}
async function firstMessage (chatChannel, backwards) { // backwards -> last message
var folderStore = $rdf.graph()
var folderFetcher = new $rdf.Fetcher(folderStore,fetcherOpts)
async function earliestSubfolder (parent) {