-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtypeIndexLogic.ts
More file actions
264 lines (246 loc) · 11.1 KB
/
typeIndexLogic.ts
File metadata and controls
264 lines (246 loc) · 11.1 KB
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
import { NamedNode, st, sym } from 'rdflib'
import { ScopedApp, TypeIndexLogic, TypeIndexScope } from '../types'
import * as debug from '../util/debug'
import { ns as namespace } from '../util/ns'
import { newThing } from '../util/utils'
import { privateTypeIndexDocument, publicTypeIndexDocument } from './typeIndexDocuments'
export function createTypeIndexLogic(store, authn, profileLogic, utilityLogic): TypeIndexLogic {
const ns = namespace
function isAbsoluteHttpUri(uri: string | null | undefined): boolean {
return !!uri && (uri.startsWith('https://') || uri.startsWith('http://'))
}
function getRegistrations(instance, theClass) {
return store
.each(undefined, ns.solid('instance'), instance)
.filter((r) => {
return store.holds(r, ns.solid('forClass'), theClass)
})
}
async function loadTypeIndexesFor(user: NamedNode): Promise<Array<TypeIndexScope>> {
if (!user) throw new Error('loadTypeIndexesFor: No user given')
const profile = await profileLogic.loadProfile(user)
let suggestion: NamedNode | null = null
try {
suggestion = suggestPublicTypeIndex(user)
} catch (err) {
const message = `User ${user} has no usable profile document directory for publicTypeIndex.`
debug.warn(message)
}
let publicTypeIndex
try {
const existingPublicTypeIndex = store.any(user, ns.solid('publicTypeIndex'), undefined, profile)
if (existingPublicTypeIndex) {
publicTypeIndex = existingPublicTypeIndex
} else if (suggestion) {
publicTypeIndex = await utilityLogic.followOrCreateLinkWithContentOnCreate(
user,
ns.solid('publicTypeIndex') as NamedNode,
suggestion,
profile,
publicTypeIndexDocument()
)
} else {
publicTypeIndex = null
}
} catch (err) {
const message = `User ${user} has no pointer in profile to publicTypeIndex file: ${err}`
debug.warn(message)
}
const publicScopes = publicTypeIndex ? [{ label: 'public', index: publicTypeIndex as NamedNode, agent: user }] : []
let preferencesFile
try {
preferencesFile = await profileLogic.silencedLoadPreferences(user)
} catch (err) {
preferencesFile = null
}
let privateScopes
if (preferencesFile) { // watch out - can be in either as spec was not clear. Legacy is profile.
// If there is a legacy one linked from the profile, use that.
// Otherwiae use or make one linked from Preferences
let suggestedPrivateTypeIndex: NamedNode | null = null
try {
suggestedPrivateTypeIndex = suggestPrivateTypeIndex(preferencesFile)
} catch (err) {
const message = `User ${user} has no usable preferences document directory for privateTypeIndex.`
debug.warn(message)
}
let privateTypeIndex
try {
const existingPrivateTypeIndex = store.any(user, ns.solid('privateTypeIndex'), undefined, profile)
if (existingPrivateTypeIndex) {
privateTypeIndex = existingPrivateTypeIndex
} else if (suggestedPrivateTypeIndex) {
privateTypeIndex = await utilityLogic.followOrCreateLinkWithContentOnCreate(
user,
ns.solid('privateTypeIndex') as NamedNode,
suggestedPrivateTypeIndex,
preferencesFile,
privateTypeIndexDocument()
)
} else {
privateTypeIndex = null
}
} catch (err) {
const message = `User ${user} has no pointer in preference file to privateTypeIndex file: ${err}`
debug.warn(message)
}
privateScopes = privateTypeIndex ? [{ label: 'private', index: privateTypeIndex as NamedNode, agent: user }] : []
} else {
privateScopes = []
}
const scopes = publicScopes.concat(privateScopes)
if (scopes.length === 0) return scopes
const files = scopes.map(scope => scope.index)
try {
await store.fetcher.load(files)
} catch (err) {
debug.warn('Problems loading type index: ', err)
}
return scopes
}
async function loadCommunityTypeIndexes(user: NamedNode): Promise<TypeIndexScope[]> {
let preferencesFile
try {
preferencesFile = await profileLogic.silencedLoadPreferences(user)
} catch (err) {
const message = `User ${user} has no pointer in profile to preferences file.`
debug.warn(message)
}
if (preferencesFile) { // For now, pick up communities as simple links from the preferences file.
const communities = store.each(user, ns.solid('community'), undefined, preferencesFile as NamedNode).concat(
store.each(user, ns.solid('community'), undefined, user.doc() as NamedNode)
)
let result = []
for (const org of communities) {
if (org.termType !== 'NamedNode' || !isAbsoluteHttpUri((org as NamedNode).uri)) {
debug.warn(`Skipping malformed community node for ${user}: ${org}`)
continue
}
try {
result = result.concat(await loadTypeIndexesFor(org as NamedNode) as any)
} catch (err) {
debug.warn(`Skipping community type indexes for ${(org as NamedNode).uri}: ${err}`)
}
}
return result
}
return [] // No communities
}
async function loadAllTypeIndexes(user: NamedNode) {
return (await loadTypeIndexesFor(user)).concat(await loadCommunityTypeIndexes(user))
}
async function getScopedAppInstances(klass: NamedNode, user: NamedNode): Promise<ScopedApp[]> {
const scopes = await loadAllTypeIndexes(user)
let scopedApps = []
for (const scope of scopes) {
const scopedApps0 = await getScopedAppsFromIndex(scope, klass) as any
scopedApps = scopedApps.concat(scopedApps0)
}
return scopedApps
}
// This is the function signature which used to be in solid-ui/logic
// Recommended to use getScopedAppInstances instead as it provides more information.
//
async function getAppInstances(klass: NamedNode): Promise<NamedNode[]> {
const user = authn.currentUser()
if (!user) throw new Error('getAppInstances: Must be logged in to find apps.')
const scopedAppInstances = await getScopedAppInstances(klass, user)
return scopedAppInstances.map(scoped => scoped.instance)
}
function docDirUri(node: NamedNode): string | null {
const doc = node.doc()
const dir = doc.dir()
if (dir?.uri && isAbsoluteHttpUri(dir.uri)) return dir.uri
const docUri = doc.uri
if (!docUri || !isAbsoluteHttpUri(docUri)) {
debug.log(`docDirUri: missing or non-http(s) doc uri for ${node?.uri}`)
return null
}
const withoutFragment = docUri.split('#')[0]
const lastSlash = withoutFragment.lastIndexOf('/')
if (lastSlash === -1) {
debug.log(`docDirUri: no slash in doc uri ${docUri}`)
return null
}
return withoutFragment.slice(0, lastSlash + 1)
}
function suggestPublicTypeIndex(me: NamedNode) {
const dirUri = docDirUri(me)
if (!dirUri) throw new Error(`suggestPublicTypeIndex: Cannot derive directory for ${me.uri}`)
return sym(dirUri + 'publicTypeIndex.ttl')
}
// Note this one is based off the pref file not the profile
function suggestPrivateTypeIndex(preferencesFile: NamedNode) {
const dirUri = docDirUri(preferencesFile)
if (!dirUri) throw new Error(`suggestPrivateTypeIndex: Cannot derive directory for ${preferencesFile.uri}`)
return sym(dirUri + 'privateTypeIndex.ttl')
}
/*
* Register a new app in a type index
* used in chat in bookmark.js (solid-ui)
* Returns the registration object if successful else null
*/
async function registerInTypeIndex(
instance: NamedNode,
index: NamedNode,
theClass: NamedNode,
// agent: NamedNode
): Promise<NamedNode | null> {
const registration = newThing(index)
const ins = [
// See https://github.com/solid/solid/blob/main/proposals/data-discovery.md
st(registration, ns.rdf('type'), ns.solid('TypeRegistration'), index),
st(registration, ns.solid('forClass'), theClass, index),
st(registration, ns.solid('instance'), instance, index)
]
try {
await store.updater.update([], ins)
} catch (err) {
const msg = `Unable to register ${instance} in index ${index}: ${err}`
console.warn(msg)
return null
}
return registration
}
async function deleteTypeIndexRegistration(item) {
const reg = store.the(null, ns.solid('instance'), item.instance, item.scope.index) as NamedNode
if (!reg) throw new Error(`deleteTypeIndexRegistration: No registration found for ${item.instance}`)
const statements = store.statementsMatching(reg, null, null, item.scope.index)
await store.updater.update(statements, [])
}
async function getScopedAppsFromIndex(scope: TypeIndexScope, theClass: NamedNode | null): Promise<ScopedApp[]> {
const index = scope.index
const results: ScopedApp[] = []
const registrations = store.statementsMatching(null, ns.solid('instance'), null, index)
.concat(store.statementsMatching(null, ns.solid('instanceContainer'), null, index))
.map(st => st.subject)
for (const reg of registrations) {
const klass = store.any(reg, ns.solid('forClass'), null, index)
if (!theClass || klass.sameTerm(theClass)) {
const instances = store.each(reg, ns.solid('instance'), null, index)
for (const instance of instances) {
results.push({ instance, type: klass, scope })
}
const containers = store.each(reg, ns.solid('instanceContainer'), null, index)
for (const instance of containers) {
await store.fetcher.load(instance)
results.push({ instance: sym(instance.value), type: klass, scope })
}
}
}
return results
}
return {
registerInTypeIndex,
getRegistrations,
loadTypeIndexesFor,
loadCommunityTypeIndexes,
loadAllTypeIndexes,
getScopedAppInstances,
getAppInstances,
suggestPublicTypeIndex,
suggestPrivateTypeIndex,
deleteTypeIndexRegistration,
getScopedAppsFromIndex
}
}