-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsolid.js
More file actions
250 lines (191 loc) · 8.61 KB
/
solid.js
File metadata and controls
250 lines (191 loc) · 8.61 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
// 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;
const solidFileClient = new SolidFileClient(solidClientAuthentication);
solidFileClient.rdf.setPrefix('schemaorg', 'https://schema.org/');
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 containerUrl = `${user.storageUrl}tasks/`;
const containmentQuads = await readSolidDocument(containerUrl, null, { ldp: 'contains' });
if (!containmentQuads)
return [];
tasksContainerUrl = containerUrl;
const tasks = [];
for (const containmentQuad of containmentQuads) {
const [typeQuad] = await readSolidDocument(containmentQuad.object.value, null, { rdf: 'type' }, { schemaorg: 'Action' });
if (!typeQuad) {
// Not a Task, we can ignore this document.
continue;
}
const taskUrl = typeQuad.subject.value;
const [descriptionQuad] = await readSolidDocument(containmentQuad.object.value, `<${taskUrl}>`, { schemaorg: 'description' });
const [statusQuad] = await readSolidDocument(containmentQuad.object.value, `<${taskUrl}>`, { schemaorg: 'actionStatus' });
tasks.push({
url: taskUrl,
description: descriptionQuad?.object.value || '-',
completed: statusQuad?.object.value === 'https://schema.org/CompletedActionStatus',
});
}
return tasks;
}
async function readSolidDocument(url, source, predicate, object, graph) {
try {
// solidFileClient.rdf.query returns an array of statements with matching terms.
// (load and cache url content)
return await solidFileClient.rdf.query(url, source, predicate, object, graph);
} catch (error) {
return null;
}
}
async function createSolidDocument(url, contents) {
const response = await solidFileClient.post(url, {
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 solidFileClient.patchFile(url, update, 'application/sparql-update');
if (!isSuccessfulStatusCode(response.status))
throw new Error(`Failed updating document at ${url}, returned status ${response.status}`);
}
async function deleteSolidDocument(url) {
const response = await solidFileClient.deleteFile(url);
if (!isSuccessfulStatusCode(response.status))
throw new Error(`Failed deleting document at ${url}, returned status ${response.status}`);
}
async function createSolidContainer(url) {
const response = await solidFileClient.createFolder(url);
if (!isSuccessfulStatusCode(response.status))
throw new Error(`Failed creating container at ${url}, returned status ${response.status}`);
return url;
}
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 [nameQuad] = await readSolidDocument(webId, null, { foaf: 'name' });
const [storageQuad] = await readSolidDocument(webId, null, { 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),
};
}
// See https://solidproject.org/TR/protocol#storage.
async function findUserStorage(url) {
url = url.replace(/#.*$/, '');
url = url.endsWith('/') ? url + '../' : url + '/../';
url = new URL(url);
const response = await solidFileClient.head(url.href);
if (response.headers.get('Link')?.includes('<http://www.w3.org/ns/pim/space#Storage>; rel="type"'))
return url.href;
// Fallback for providers that don't advertise storage properly.
if (url.pathname === '/')
return url.href;
return findUserStorage(url.href);
}
function escapeText(text) {
return text.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}