-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsolid.js
More file actions
280 lines (217 loc) · 9.39 KB
/
solid.js
File metadata and controls
280 lines (217 loc) · 9.39 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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
// You can find the basic Solid concepts explained in the Glossary.md file, inline comments talk about
// the specifics of how this application is implemented.
let user, tasksContainerUrl;
async function restoreSession() {
// This function uses Inrupt's authentication library to restore a previous session. If you were
// already logged into the application last time that you used it, this will trigger a redirect that
// takes you back to the application. This usually happens without user interaction, but if you hadn't
// logged in for a while, your identity provider may ask for your credentials again.
//
// After a successful login, this will also read the profile from your POD.
//
// @see https://docs.inrupt.com/developer-tools/javascript/client-libraries/tutorial/authenticate-browser/
try {
await solidClientAuthentication.handleIncomingRedirect({ restorePreviousSession: true });
const session = solidClientAuthentication.getDefaultSession();
if (!session.info.isLoggedIn)
return false;
user = await fetchUserProfile(session.info.webId);
return user;
} catch (error) {
alert(error.message);
return false;
}
}
function getLoginUrl() {
// Asking for a login url in Solid is kind of tricky. In a real application, you should be
// asking for a user's webId, and reading the user's profile you would be able to obtain
// the url of their identity provider. However, most users may not know what their webId is,
// and they introduce the url of their issue provider directly. In order to simplify this
// example, we just use the base domain of the url they introduced, and this should work
// most of the time.
const url = prompt('Introduce your Solid login url');
if (!url)
return null;
const loginUrl = new URL(url);
loginUrl.hash = '';
loginUrl.pathname = '';
return loginUrl.href;
}
function performLogin(loginUrl) {
solidClientAuthentication.login({
oidcIssuer: loginUrl,
redirectUrl: window.location.href,
clientName: 'Hello World',
});
}
async function performLogout() {
await solidClientAuthentication.logout();
}
async function performTaskCreation(description) {
// Data discovery mechanisms are still being defined in Solid, but so far it is clear that
// applications should not hard-code the url of their containers like we are doing in this
// example.
//
// In a real application, you should use one of these two alternatives:
//
// - The Type index. This is the one that most applications are using in practice today:
// https://github.com/solid/solid/blob/main/proposals/data-discovery.md#type-index-registry
//
// - SAI, or Solid App Interoperability. This one is still being defined:
// https://solid.github.io/data-interoperability-panel/specification/
if (!tasksContainerUrl)
tasksContainerUrl = await createSolidContainer(user.storageUrl, 'tasks');
const documentUrl = await createSolidDocument(tasksContainerUrl, `
@prefix schema: <https://schema.org/> .
<#it>
a schema:Action ;
schema:actionStatus schema:PotentialActionStatus ;
schema:description "${escapeText(description)}" .
`);
const taskUrl = `${documentUrl}#it`;
return { url: taskUrl, description };
}
async function performTaskUpdate(taskUrl, completed) {
const documentUrl = getSolidDocumentUrl(taskUrl);
await updateSolidDocument(documentUrl, `
DELETE DATA {
<#it>
<https://schema.org/actionStatus>
<https://schema.org/${completed ? 'PotentialActionStatus' : 'CompletedActionStatus'}> .
} ;
INSERT DATA {
<#it>
<https://schema.org/actionStatus>
<https://schema.org/${completed ? 'CompletedActionStatus' : 'PotentialActionStatus'}> .
}
`);
}
async function performTaskDeletion(taskUrl) {
const documentUrl = getSolidDocumentUrl(taskUrl);
await deleteSolidDocument(documentUrl);
}
async function loadTasks() {
// In a real application, you shouldn't hard-code the path to the container like we're doing here.
// Read more about this in the comments on the performTaskCreation function.
const containerQuads = await readSolidDocument(`${user.storageUrl}tasks/`);
if (!containerQuads)
return [];
tasksContainerUrl = `${user.storageUrl}tasks/`;
const tasks = [];
const containmentQuads = containerQuads.filter(quad => quad.predicate.value === 'http://www.w3.org/ns/ldp#contains');
for (const containmentQuad of containmentQuads) {
const documentQuads = await readSolidDocument(containmentQuad.object.value);
const typeQuad = documentQuads.find(
quad =>
quad.predicate.value === 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type' &&
quad.object.value === 'https://schema.org/Action'
);
if (!typeQuad) {
// Not a Task, we can ignore this document.
continue;
}
const taskUrl = typeQuad.subject.value;
const descriptionQuad = documentQuads.find(
quad =>
quad.subject.value === taskUrl &&
quad.predicate.value === 'https://schema.org/description'
);
const statusQuad = documentQuads.find(
quad =>
quad.subject.value === taskUrl &&
quad.predicate.value === 'https://schema.org/actionStatus'
);
tasks.push({
url: taskUrl,
description: descriptionQuad?.object.value || '-',
completed: statusQuad?.object.value === 'https://schema.org/CompletedActionStatus',
});
}
return tasks;
}
async function readSolidDocument(url) {
try {
const response = await solidClientAuthentication.fetch(url, { headers: { Accept: 'text/turtle' } });
if (!isSuccessfulStatusCode(response.status))
return null;
const data = await response.text();
const parser = new N3.Parser({ baseIRI: url });
return parser.parse(data);
} catch (error) {
return null;
}
}
async function createSolidDocument(url, contents) {
const response = await solidClientAuthentication.fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'text/turtle' },
body: contents,
});
if (!isSuccessfulStatusCode(response.status))
throw new Error(`Failed creating document at ${url}, returned status ${response.status}`);
const location = response.headers.get('Location');
return new URL(location, url).href;
}
async function updateSolidDocument(url, update) {
const response = await solidClientAuthentication.fetch(url, {
method: 'PATCH',
headers: { 'Content-Type': 'application/sparql-update' },
body: update,
});
if (!isSuccessfulStatusCode(response.status))
throw new Error(`Failed updating document at ${url}, returned status ${response.status}`);
}
async function deleteSolidDocument(url) {
const response = await solidClientAuthentication.fetch(url, { method: 'DELETE' });
if (!isSuccessfulStatusCode(response.status))
throw new Error(`Failed deleting document at ${url}, returned status ${response.status}`);
}
async function createSolidContainer(url, name) {
const response = await solidClientAuthentication.fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'text/turtle',
'Link': '<http://www.w3.org/ns/ldp#BasicContainer>; rel="type"',
'Slug': name,
},
});
if (!isSuccessfulStatusCode(response.status))
throw new Error(`Failed creating container at ${url}, returned status ${response.status}`);
const location = response.headers.get('Location');
return new URL(location, url).href;
}
function isSuccessfulStatusCode(statusCode) {
return Math.floor(statusCode / 100) === 2;
}
function getSolidDocumentUrl(resourceUrl) {
const url = new URL(resourceUrl);
url.hash = '';
return url.href;
}
async function fetchUserProfile(webId) {
const profileQuads = await readSolidDocument(webId);
const nameQuad = profileQuads.find(quad => quad.predicate.value === 'http://xmlns.com/foaf/0.1/name');
const storageQuad = profileQuads.find(quad => quad.predicate.value === 'http://www.w3.org/ns/pim/space#storage');
return {
url: webId,
name: nameQuad?.object.value || 'Anonymous',
// WebIds may declare more than one storage url, so in a real application you should
// ask which one to use if that happens. In this app, in order to keep it simple, we'll
// just use the first one. If none is declared in the profile, we'll search for it.
storageUrl: storageQuad?.object.value || await findUserStorage(webId),
};
}
async function findUserStorage(url) {
url = url.replace(/#.*$/, '');
url = url.endsWith('/') ? url + '../' : url + '/../';
url = new URL(url);
const response = await solidClientAuthentication.fetch(url.href);
if (response.headers.get('Link')?.includes('<http://www.w3.org/ns/pim/space#Storage>; rel="type"'))
return url.href;
if (url.pathname === '/')
return url.href;
return findUserStorage(url.href);
}
function escapeText(text) {
return text.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}