-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
314 lines (253 loc) · 9.35 KB
/
app.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
import { html, Component, render } from './js/spux.js'
import { getPath, getQueryStringValue, loadFile, saveFile } from './util.js'
import { findNestedObjectById } from './js/linkedobjects.js'
// import './css/style.css'
import './js/dior.js'
// await awaitForNostr();
// const userPublicKey = await window.nostr.getPublicKey();
function awaitForNostr() {
return new Promise(resolve => {
let intervalTime = 2;
const maxIntervalTime = 500;
const maxElapsedTime = 5000;
let elapsedTime = 0;
const intervalId = setInterval(() => {
console.log(intervalTime, elapsedTime)
elapsedTime += intervalTime;
if (typeof window.nostr !== 'undefined') {
console.log('nostr found')
clearInterval(intervalId);
resolve();
} else if (elapsedTime >= maxElapsedTime) {
clearInterval(intervalId);
resolve();
} else {
intervalTime = Math.min(intervalTime * 1.5, maxIntervalTime);
}
}, intervalTime);
});
}
class UserProfile extends Component {
render() {
const { userPublicKey, name, picture, about, banner } = this.props;
const shortenedPubKey = userPublicKey ? userPublicKey.slice(0, 16) : '';
const irisLink = `https://iris.to/${userPublicKey}`;
return html`
<div class="user-profile">
${banner ? html`<div class="banner"><img src="${banner}" alt="Banner" /></div>` : ''}
<br/>
<h2>${name}</h2>
<img src="${picture}" alt="Profile Picture" class="user-picture" />
${userPublicKey ? html`<p>Pubkey: <a href="${irisLink}" target="_blank">${shortenedPubKey}</a></p>` : ''}
${about ? html`<p>${about}</p>` : ''}
</div>
`;
}
}
class SocialLinks extends Component {
render() {
const { website, github, apps, twitter } = this.props;
return html`
<div class="social-links">
<h3>Connect</h3>
${website ? html`<a href="${website}" target="_blank">Website</a>` : ""}
${github ? html`<br/><a href="https://github.com/${github}" target="_blank">Github</a>` : ""}
${twitter ? html`<br/><a href="https://twitter.com/${twitter}" target="_blank">Twitter</a>` : ""}
<h3>Apps <a style="text-decoration:none" target="_blank" href="https://nosdav.com/applist/?uri=${location.href}">🔗</a></h3>
${apps.map(app => html`
<a href="${app.uri}" target="_blank">${app.label || app.uri}</a><br/>
`)}
</div>
`
}
}
// APP
export class App extends Component {
constructor() {
super();
this.fetchProfile = this.fetchProfile.bind(this);
const serverUrl = getQueryStringValue('storage') || di.data[0].storage || 'https://nosdav.nostr.rocks'
const mode = getQueryStringValue('mode') || di.data[0].m || 'm'
const uri = getQueryStringValue('uri') || di.data[0].uri || 'profile.json'
const profilePubkey = getQueryStringValue('pubkey')
var key
if (di.data[0].mainEntity['@id']) {
key = di.data[0].mainEntity['@id'].replace('nostr:pubkey:', '')
} else {
key = this.userPublicKey
}
var apps = findNestedObjectById(di.data, 'nostr:pubkey:' + key)?.mainEntity?.app || []
this.state = {
userPublicKey: null,
filename: uri,
fileContent: '',
bookmarks: [],
newBookmarkUrl: '',
serverUrl: serverUrl,
mode: mode,
profilePubkey: profilePubkey,
apps: apps
};
}
saveProfile = async () => {
const { userPublicKey, serverUrl, mode, filename } = this.state;
di.data[0].mainEntity['@id'] = 'nostr:pubkey:' + userPublicKey;
async function replaceScriptTagContent() {
const improvedRegex = /(<script[^>]*type\s*=\s*(['"])application[^>]*\2[^>]*>)([\s\S]*?)(<\/script>)/gim;
// Fetch the current HTML page content
const response = await fetch(location.href);
const html = await response.text();
// Replace the script tag content with a pretty-printed, stringified version of di.data
const replacedScriptTagContent = html.replace(improvedRegex, (match, openingTag, quote, content, closingTag) => {
return `${openingTag}${JSON.stringify(di.data, null, 2)}${closingTag}`;
});
const newHtml = replaceRelativePath(replacedScriptTagContent);
// Log the new output to the console
console.log(newHtml);
return newHtml;
}
function replaceRelativePath(html) {
const baseUrl = new URL(location.href);
baseUrl.pathname = baseUrl.pathname.substring(0, baseUrl.pathname.lastIndexOf('/') + 1);
const relativePathRegex = /(\.\/)/g;
return html.replace(relativePathRegex, (match) => {
return `${baseUrl.origin}${baseUrl.pathname}`;
});
}
// Create a wrapper function to call the replaceScriptTagContent function
var fileContent = await replaceScriptTagContent();
// fileContent = replaceRelativePath(fileContent);
const success = await saveFile(serverUrl, userPublicKey, filename, mode, fileContent);
if (!success) {
alert('Error saving profile');
}
};
userLogin = async () => {
await awaitForNostr();
var userPublicKey = await window.nostr.getPublicKey();
if (this.state.profilePubkey) {
userPublicKey = this.state.profilePubkey;
}
var key
if (!di.data[0].mainEntity['@id']) {
di.data[0].mainEntity['@id'] = 'nostr:pubkey:' + userPublicKey
key = userPublicKey
} else {
key = di.data[0].mainEntity['@id'].replace('nostr:pubkey:', '')
}
console.log(`Logged in with public key: ${userPublicKey}`);
await this.setState({ userPublicKey: userPublicKey, apps: findNestedObjectById(di.data, 'nostr:pubkey:' + key)?.mainEntity?.app || [] })
// Use an arrow function here
var key
if (di.data[0].mainEntity && di.data[0].mainEntity['@id']) {
key = di.data[0].mainEntity['@id'].replace('nostr:pubkey:', '')
} else {
key = this.state.userPublicKey
}
this.fetchProfile(key, () => this.render());
};
getRelay() {
// const relay = getQueryStringValue('relay') || di.data[0].relay || 'wss://nostr-pub.wellorder.net';
const relay = getQueryStringValue('relay') || di.data[0].relay || 'wss://relay.damus.io/';
return relay
}
async componentDidMount() {
var key
if (di.data[0].mainEntity && di.data[0].mainEntity['@id']) {
key = di.data[0].mainEntity['@id'].replace('nostr:pubkey:', '')
} else {
await this.userLogin()
key = this.state.userPublicKey
}
this.fetchProfile(key, this.render.bind(this))
}
// fetchProfile.js
fetchProfile(pubkey, render) {
const NOSTR_RELAY_URL = this.getRelay()
var key
if (di.data[0].mainEntity && di.data[0].mainEntity['@id']) {
key = di.data[0].mainEntity['@id'].replace('nostr:pubkey:', '')
} else {
key = this.state.userPublicKey
}
let wss = new WebSocket(NOSTR_RELAY_URL);
let kind = 0;
let id = 'profile';
wss.onopen = function () {
const req = `["REQ", "${id}", { "kinds": [${kind}], "authors": ["${key}"] }]`;
wss.send(req);
};
// Use an arrow function here
wss.onmessage = (msg) => {
const response = JSON.parse(msg.data);
if (response && response[2]) {
const data = response[2];
console.log(data);
const content = JSON.parse(data.content);
this.setState({
name: content.name,
picture: content.picture,
website: content.website,
about: content.about,
banner: content.banner,
github: content.identities?.[0]?.claim,
});
di.data[0].mainEntity.name = content.name
di.data[0].mainEntity.image = content.picture
di.data[0].mainEntity.url = content.website
di.data[0].mainEntity.description = content.about
di.data[0].mainEntity.banner = content.banner
di.data[0].mainEntity.github = content.identities?.[0]?.claim
render();
} else {
console.error('Invalid or undefined data received:', msg.data);
}
};
}
render() {
const { userPublicKey, fileContent, name, picture, website, about, banner, github } = this.state;
var key
if (di.data[0].mainEntity && di.data[0].mainEntity['@id']) {
key = di.data[0].mainEntity['@id'].replace('nostr:pubkey:', '')
} else {
key = this.state.userPublicKey
}
var apps = findNestedObjectById(di.data, 'nostr:pubkey:' + key)?.app || []
const uriWithLabels = apps.map((uri) => {
const foundObject = findNestedObjectById(di.data, uri);
const label = foundObject ? foundObject.label : null;
return { uri, label };
});
console.log(uriWithLabels);
return html`
<div id="container">
<div class="content">
<${UserProfile}
userPublicKey="${key}"
name="${name}"
picture="${picture}"
about="${about}"
banner="${banner}"
/>
<${SocialLinks}
website="${website}"
github="${github}"
apps="${uriWithLabels}"
/>
</div>
<div class="file-section">
<div>
${userPublicKey
? html`
<button id="save" onClick="${this.saveProfile}">Save Profile</button>
`
: html` <button id="login" onClick="${this.userLogin}">
Login
</button>`}
</div>
</div>
</div>
`
}
}
render(html` <${App} /> `, document.body)