Run prettier.

This commit is contained in:
Cory McWilliams 2024-02-24 11:09:34 -05:00
parent 8e7e0ed490
commit d5267be38c
90 changed files with 5789 additions and 2265 deletions

View File

@ -3,8 +3,3 @@ useTabs: true
semi: true
singleQuote: true
bracketSpacing: false
# overrides:
# - files: '**/*.json'
# options:
# useTabs: false
# tabWidth: 2

View File

@ -1,4 +1,5 @@
# Tilde Friends
Tilde Friends is a tool for making and sharing.
A public instance lives at https://www.tildefriends.net/.
@ -7,37 +8,42 @@ It is both a peer-to-peer social network client, participating in Secure
Scuttlebutt, as well as a platform for writing and running web applications.
## Goals
1. Make it easy and fun to run all sorts of web applications.
2. Provide security that is easy to understand and protects your data.
3. Make creating and sharing web applications accessible to anyone with a
browser.
## Building
Builds on Linux (x86_64 and aarch64), MacOS, OpenBSD, and Haiku. Builds for
Builds on Linux (x86_64 and aarch64), MacOS, OpenBSD, and Haiku. Builds for
all of those host platforms plus mingw64, iOS, and android.
1. Requires openssl (`libssl-dev`, in debian-speak). All other dependencies
1. Requires openssl (`libssl-dev`, in debian-speak). All other dependencies
are kept up to date in the tree.
2. To build, run `make debug` or `make release`. An executable will be
2. To build, run `make debug` or `make release`. An executable will be
generated in a subdirectory of `out/`.
3. It's possible to build for Android, iOS, and Windows on Linux, if you have
the right dependencies in the right places. `make windebug winrelease
iosdebug-ipa iosrelease-ipa release-apk`.
the right dependencies in the right places. `make windebug winrelease
iosdebug-ipa iosrelease-ipa release-apk`.
4. To build in docker, `docker build .`.
5. `make format` will normalize formatting to the coding standard.
## Running
By default, running the built `tildefriends` executable will start a web server
at <http://localhost:12345/>. `tildefriends -h` lists further options.
at <http://localhost:12345/>. `tildefriends -h` lists further options.
The first user to create an account and log in will be granted administrative
privileges. Further administration can be done at
privileges. Further administration can be done at
<http://localhost:12345/~core/admin/>.
## Documentation
Docs are a work in progress:
<https://www.tildefriends.net/~cory/wiki/#test-wiki/tf-app-quick-reference>.
## License
All code unless otherwise noted in is provided under the
[MIT](https://opensource.org/licenses/MIT) license.

View File

@ -1,4 +1,4 @@
{
"type": "tildefriends-app",
"emoji": "🎛"
}
}

View File

@ -18,9 +18,13 @@ async function main() {
for (let user of await core.users()) {
data.users[user] = await core.permissionsForUser(user);
}
await app.setDocument(utf8Decode(getFile('index.html')).replace('$data', JSON.stringify(data)));
await app.setDocument(
utf8Decode(getFile('index.html')).replace('$data', JSON.stringify(data))
);
} catch {
await app.setDocument('<span style="color: #f00">Only an administrator can modify these settings.</span>');
await app.setDocument(
'<span style="color: #f00">Only an administrator can modify these settings.</span>'
);
}
}
main();
main();

View File

@ -1,10 +1,12 @@
<!DOCTYPE html>
<!doctype html>
<html style="width: 100%">
<head>
<script>const g_data = $data;</script>
<script>
const g_data = $data;
</script>
</head>
<body style="color: #fff; width: 100%">
<h1>Tilde Friends Administration</h1>
</body>
<script type="module" src="script.js"></script>
</html>
</html>

View File

@ -3,25 +3,32 @@ import * as tfrpc from '/static/tfrpc.js';
function delete_user(user) {
if (confirm(`Are you sure you want to delete the user "${user}"?`)) {
tfrpc.rpc.delete_user(user).then(function() {
alert(`User "${user}" deleted successfully.`);
}).catch(function(error) {
alert(`Failed to delete user "${user}": ${JSON.stringify(error, null, 2)}.`);
});
tfrpc.rpc
.delete_user(user)
.then(function () {
alert(`User "${user}" deleted successfully.`);
})
.catch(function (error) {
alert(
`Failed to delete user "${user}": ${JSON.stringify(error, null, 2)}.`
);
});
}
}
function global_settings_set(key, value) {
tfrpc.rpc.global_settings_set(key, value).then(function() {
alert(`Set "${key}" to "${value}".`);
}).catch(function(error) {
alert(`Failed to set "${key}": ${JSON.stringify(error, null, 2)}.`);
});
tfrpc.rpc
.global_settings_set(key, value)
.then(function () {
alert(`Set "${key}" to "${value}".`);
})
.catch(function (error) {
alert(`Failed to set "${key}": ${JSON.stringify(error, null, 2)}.`);
});
}
window.addEventListener('load', function() {
const permission_template = (permission) =>
html` <code>${permission}</code>`;
window.addEventListener('load', function () {
const permission_template = (permission) => html` <code>${permission}</code>`;
function input_template(key, description) {
if (description.type === 'boolean') {
return html`
@ -62,26 +69,24 @@ window.addEventListener('load', function() {
}
const user_template = (user, permissions) => html`
<li>
<button @click=${(e) => delete_user(user)}>
Delete
</button>
${user}:
${permissions.map(x => permission_template(x))}
<button @click=${(e) => delete_user(user)}>Delete</button>
${user}: ${permissions.map((x) => permission_template(x))}
</li>
`;
const users_template = (users) =>
html`<h2>Users</h2>
<ul>
${Object.entries(users).map(u => user_template(u[0], u[1]))}
</ul>`;
<ul>
${Object.entries(users).map((u) => user_template(u[0], u[1]))}
</ul>`;
const page_template = (data) =>
html`<div style="padding: 0; margin: 0; width: 100%; max-width: 100%">
<h2>Global Settings</h2>
<div>
${Object.keys(data.settings).sort().map(x => html`${input_template(x, data.settings[x])}`)}
${Object.keys(data.settings)
.sort()
.map((x) => html`${input_template(x, data.settings[x])}`)}
</div>
${users_template(data.users)}
</div>
`;
</div> `;
render(page_template(g_data), document.body);
});
});

View File

@ -2,4 +2,4 @@
"type": "tildefriends-app",
"emoji": "📜",
"previous": "&miGORZ8BwjHg2YO0t4bms6SI28XWPYqnqOZ8u9zsbZc=.sha256"
}
}

View File

@ -219,7 +219,7 @@ Parses an HTTP response.
* *Object* An object with **bytes_parsed**, **minor_version**, **status**, **message**, and **headers** fields on successful parse.
`;
docs['sha1Digest()'] =`
docs['sha1Digest()'] = `
Calculates a SHA1 digest.
Completes synchronously.
@ -353,4 +353,4 @@ Call a remote function.
* **...** Parameters to pass to the function.
### Returns
The return value of the called function.
`;
`;

View File

@ -2,4 +2,4 @@
"type": "tildefriends-app",
"emoji": "💻",
"previous": "&RdVEsVscZm3aWzcMrEZS8mskO5tUmvaEUihex2MMfZQ=.sha256"
}
}

View File

@ -26,14 +26,15 @@ async function fetch_info(apps) {
async function fetch_shared_apps() {
let messages = {};
await ssb.sqlAsync(`
await ssb.sqlAsync(
`
SELECT messages.*
FROM messages_fts('"application/tildefriends"')
JOIN messages ON messages.rowid = messages_fts.rowid
ORDER BY timestamp
`,
[],
function(row) {
function (row) {
let content = JSON.parse(row.content);
for (let mention of content.mentions) {
if (mention?.type === 'application/tildefriends') {
@ -44,10 +45,13 @@ async function fetch_shared_apps() {
};
}
}
});
}
);
let result = {};
for (let app of Object.values(messages).sort((x, y) => y.message.timestamp - x.message.timestamp)) {
for (let app of Object.values(messages).sort(
(x, y) => y.message.timestamp - x.message.timestamp
)) {
let app_object = JSON.parse(utf8Decode(await ssb.blobGet(app.blob)));
if (app_object) {
app_object.blob_id = app.blob;

View File

@ -1,5 +1,5 @@
{
"type": "tildefriends-app",
"emoji": "🪵",
"previous": "&TIrBnpN3iz3O9L9MCCteAcVJZjA83EKdcfu4SCM76VE=.sha256"
}
"type": "tildefriends-app",
"emoji": "🪵",
"previous": "&TIrBnpN3iz3O9L9MCCteAcVJZjA83EKdcfu4SCM76VE=.sha256"
}

View File

@ -5,4 +5,4 @@ async function main() {
await app.setDocument(blog.render_html(blogs));
}
main();
main();

View File

@ -1,11 +1,19 @@
import * as commonmark from './commonmark.min.js';
function escape(text) {
return (text ?? '').replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
return (text ?? '')
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;');
}
function escapeAttribute(text) {
return (text ?? '').replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&#39;');
return (text ?? '')
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#39;');
}
export async function get_blog_message(id) {
@ -13,7 +21,7 @@ export async function get_blog_message(id) {
await ssb.sqlAsync(
'SELECT author, timestamp, content FROM messages WHERE id = ?',
[id],
function(row) {
function (row) {
let content = JSON.parse(row.content);
message = {
author: row.author,
@ -21,7 +29,8 @@ export async function get_blog_message(id) {
blog: content?.blog,
title: content?.title,
};
});
}
);
if (message) {
await ssb.sqlAsync(
`
@ -34,9 +43,10 @@ export async function get_blog_message(id) {
ORDER BY sequence DESC LIMIT 1
`,
[message.author],
function(row) {
function (row) {
message.name = row.name;
});
}
);
}
return message;
}
@ -51,8 +61,12 @@ export function markdown(md) {
node = event.node;
if (event.entering) {
if (node.destination?.startsWith('&')) {
node.destination = '/' + node.destination + '/view?filename=' + node.firstChild?.literal;
} else if (node.destination?.startsWith('@') || node.destination?.startsWith('%')) {
node.destination =
'/' + node.destination + '/view?filename=' + node.firstChild?.literal;
} else if (
node.destination?.startsWith('@') ||
node.destination?.startsWith('%')
) {
node.destination = '/~core/ssb/#' + escape(node.destination);
}
}
@ -107,7 +121,7 @@ export function render_html(blogs) {
<h1>🪵Tilde Friends Blog</h1>
<div style="font-size: xx-small; vertical-align: middle"><a href="/~cory/blog/atom">atom feed</a></div>
</div>
${blogs.map(blog_post => render_blog_post(blog_post)).join('\n')}
${blogs.map((blog_post) => render_blog_post(blog_post)).join('\n')}
</body>
</html>`;
}
@ -135,14 +149,15 @@ export function render_atom(blogs) {
<link href="${core.url}"/>
<id>${core.url}</id>
<updated>${new Date().toString()}</updated>
${blogs.map(blog_post => render_blog_post_atom(blog_post)).join('\n')}
${blogs.map((blog_post) => render_blog_post_atom(blog_post)).join('\n')}
</feed>`;
}
export async function get_posts() {
let blogs = [];
let ids = await ssb.getIdentities();
await ssb.sqlAsync(`
await ssb.sqlAsync(
`
WITH
blogs AS (
SELECT
@ -182,8 +197,11 @@ export async function get_posts() {
JOIN public ON public.author = blogs.author
LEFT OUTER JOIN names ON names.author = blogs.author
ORDER BY blogs.timestamp DESC LIMIT 20
`, [JSON.stringify(ids)], function(row) {
blogs.push(row);
});
`,
[JSON.stringify(ids)],
function (row) {
blogs.push(row);
}
);
return blogs;
}
}

View File

@ -2,30 +2,50 @@ import * as blog from './blog.js';
async function main() {
if (request.path.startsWith('%') && request.path.endsWith('.sha256')) {
let id = request.path.startsWith('%25') ? '%' + request.path.substring(3) : request.path;
let id = request.path.startsWith('%25')
? '%' + request.path.substring(3)
: request.path;
let message = await blog.get_blog_message(id);
if (message) {
respond({data: await blog.render_blog_post_html(message), content_type: 'text/html; charset=utf-8'});
respond({
data: await blog.render_blog_post_html(message),
content_type: 'text/html; charset=utf-8',
});
} else {
respond({data: `Message ${id} not found.`, content_type: 'text/html; charset=utf-8'});
respond({
data: `Message ${id} not found.`,
content_type: 'text/html; charset=utf-8',
});
}
} else if (request.path == 'atom') {
let blogs = await blog.get_posts();
respond({data: blog.render_atom(blogs), content_type: 'application/atom+xml'});
respond({
data: blog.render_atom(blogs),
content_type: 'application/atom+xml',
});
} else {
let blogs = await blog.get_posts();
for (let blog_post of blogs) {
let title = (blog_post.title || '').replaceAll(/\W/g, '_').toLowerCase();
if (request.path === title) {
respond({data: await blog.render_blog_post_html(blog_post), content_type: 'text/html; charset=utf-8'});
respond({
data: await blog.render_blog_post_html(blog_post),
content_type: 'text/html; charset=utf-8',
});
return;
}
}
respond({data: blog.render_html(blogs), content_type: 'text/html; charset=utf-8'});
respond({
data: blog.render_html(blogs),
content_type: 'text/html; charset=utf-8',
});
}
}
main().catch(function(error) {
respond({data: `<!DOCTYPE html>
<pre style="color: #f00">${error.message}\n${error.stack}</pre>`, content_type: 'text/html'});
});
main().catch(function (error) {
respond({
data: `<!DOCTYPE html>
<pre style="color: #f00">${error.message}\n${error.stack}</pre>`,
content_type: 'text/html',
});
});

View File

@ -51,7 +51,7 @@ async function key_list(db) {
app.setDocument(doc);
}
core.register('message', async function(message) {
core.register('message', async function (message) {
if (message.event == 'hashChange') {
let hash = message.hash.substring(1);
if (hash.startsWith(':shared:')) {
@ -67,4 +67,4 @@ core.register('message', async function(message) {
}
});
database_list();
database_list();

View File

@ -1,4 +1,4 @@
{
"type": "tildefriends-app",
"emoji": "➡️"
}
}

View File

@ -2,7 +2,7 @@ let g_about_cache = {};
async function query(sql, args) {
let result = [];
await ssb.sqlAsync(sql, args, function(row) {
await ssb.sqlAsync(sql, args, function (row) {
result.push(row);
});
return result;
@ -21,7 +21,8 @@ async function contacts_internal(id, last_row_id, following, max_row_id) {
json_extract(content, '$.type') = 'contact'
ORDER BY sequence
`,
[id, last_row_id, max_row_id]);
[id, last_row_id, max_row_id]
);
for (let row of contacts) {
let contact = JSON.parse(row.content);
if (contact.following === true) {
@ -42,15 +43,34 @@ async function contact(id, last_row_id, following, max_row_id) {
return await contacts_internal(id, last_row_id, following, max_row_id);
}
async function following_deep_internal(ids, depth, blocking, last_row_id, following, max_row_id) {
let contacts = await Promise.all([...new Set(ids)].map(x => contact(x, last_row_id, following, max_row_id)));
async function following_deep_internal(
ids,
depth,
blocking,
last_row_id,
following,
max_row_id
) {
let contacts = await Promise.all(
[...new Set(ids)].map((x) => contact(x, last_row_id, following, max_row_id))
);
let result = {};
for (let i = 0; i < ids.length; i++) {
let id = ids[i];
let contact = contacts[i];
let all_blocking = Object.assign({}, contact.blocking, blocking);
let found = Object.keys(contact.following).filter(y => !all_blocking[y]);
let deeper = depth > 1 ? await following_deep_internal(found, depth - 1, all_blocking, last_row_id, following, max_row_id) : [];
let found = Object.keys(contact.following).filter((y) => !all_blocking[y]);
let deeper =
depth > 1
? await following_deep_internal(
found,
depth - 1,
all_blocking,
last_row_id,
following,
max_row_id
)
: [];
result[id] = [id, ...found, ...deeper];
}
return [...new Set(Object.values(result).flat())];
@ -68,10 +88,22 @@ async function following_deep(ids, depth, blocking) {
last_row_id: 0,
};
}
let max_row_id = (await query(`
let max_row_id = (
await query(
`
SELECT MAX(rowid) AS max_row_id FROM messages
`, []))[0].max_row_id;
let result = await following_deep_internal(ids, depth, blocking, cache.last_row_id, cache.following, max_row_id);
`,
[]
)
)[0].max_row_id;
let result = await following_deep_internal(
ids,
depth,
blocking,
cache.last_row_id,
cache.following,
max_row_id
);
cache.last_row_id = max_row_id;
let store = JSON.stringify(cache);
await db.set('following', store);
@ -90,13 +122,15 @@ async function fetch_about(db, ids, users) {
};
}
let max_row_id = 0;
await ssb.sqlAsync(`
await ssb.sqlAsync(
`
SELECT MAX(rowid) AS max_row_id FROM messages
`,
[],
function(row) {
function (row) {
max_row_id = row.max_row_id;
});
}
);
for (let id of Object.keys(cache.about)) {
if (ids.indexOf(id) == -1) {
delete cache.about[id];
@ -129,17 +163,21 @@ async function fetch_about(db, ids, users) {
ORDER BY messages.author, messages.sequence
`,
[
JSON.stringify(ids.filter(id => cache.about[id])),
JSON.stringify(ids.filter(id => !cache.about[id])),
JSON.stringify(ids.filter((id) => cache.about[id])),
JSON.stringify(ids.filter((id) => !cache.about[id])),
cache.last_row_id,
max_row_id,
]);
]
);
for (let about of abouts) {
let content = JSON.parse(about.content);
if (content.about === about.author) {
delete content.type;
delete content.about;
cache.about[about.author] = Object.assign(cache.about[about.author] || {}, content);
cache.about[about.author] = Object.assign(
cache.about[about.author] || {},
content
);
}
}
cache.last_row_id = max_row_id;
@ -155,41 +193,41 @@ async function getAbout(db, id) {
if (g_about_cache[id]) {
return g_about_cache[id];
}
let o = await db.get(id + ":about");
let o = await db.get(id + ':about');
const k_version = 4;
let f = o ? JSON.parse(o) : o;
if (!f || f.version != k_version) {
f = {about: {}, sequence: 0, version: k_version};
}
await ssb.sqlAsync(
"SELECT "+
" sequence, "+
" content "+
"FROM messages "+
"WHERE "+
" author = ?1 AND "+
" sequence > ?2 AND "+
" json_extract(content, '$.type') = 'about' AND "+
" json_extract(content, '$.about') = ?1 "+
"UNION SELECT MAX(sequence) as sequence, NULL FROM messages WHERE author = ?1 "+
"ORDER BY sequence",
'SELECT ' +
' sequence, ' +
' content ' +
'FROM messages ' +
'WHERE ' +
' author = ?1 AND ' +
' sequence > ?2 AND ' +
" json_extract(content, '$.type') = 'about' AND " +
" json_extract(content, '$.about') = ?1 " +
'UNION SELECT MAX(sequence) as sequence, NULL FROM messages WHERE author = ?1 ' +
'ORDER BY sequence',
[id, f.sequence],
function(row) {
function (row) {
f.sequence = row.sequence;
if (row.content) {
let about = {};
try {
about = JSON.parse(row.content);
} catch {
}
} catch {}
delete about.about;
delete about.type;
f.about = Object.assign(f.about, about);
}
});
}
);
let j = JSON.stringify(f);
if (o != j) {
await db.set(id + ":about", j);
await db.set(id + ':about', j);
}
g_about_cache[id] = f.about;
return f.about;
@ -198,15 +236,15 @@ async function getAbout(db, id) {
async function getSize(db, id) {
let size = 0;
await ssb.sqlAsync(
"SELECT (LENGTH(author) * COUNT(*) + SUM(LENGTH(content)) + SUM(LENGTH(id))) AS size FROM messages WHERE author = ?1",
'SELECT (LENGTH(author) * COUNT(*) + SUM(LENGTH(content)) + SUM(LENGTH(id))) AS size FROM messages WHERE author = ?1',
[id],
function (row) {
size += row.size;
});
}
);
return size;
}
async function getSizes(ids) {
let sizes = {};
await ssb.sqlAsync(
@ -221,7 +259,8 @@ async function getSizes(ids) {
[JSON.stringify(ids)],
function (row) {
sizes[row.author] = row.size;
});
}
);
return sizes;
}
@ -241,7 +280,10 @@ function niceSize(bytes) {
}
function escape(value) {
return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
return value
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;');
}
async function main() {
@ -249,19 +291,27 @@ async function main() {
let db = await database('ssb');
let whoami = await ssb.getIdentities();
let tree = '';
await app.setDocument(`<pre style="color: #fff">Enumerating followed users...</pre>`);
await app.setDocument(
`<pre style="color: #fff">Enumerating followed users...</pre>`
);
let following = await following_deep(whoami, 2, {});
await app.setDocument(`<pre style="color: #fff">Getting names and sizes...</pre>`);
await app.setDocument(
`<pre style="color: #fff">Getting names and sizes...</pre>`
);
let [about, sizes] = await Promise.all([
fetch_about(db, following, {}),
getSizes(following),
]);
await app.setDocument(`<pre style="color: #fff">Finishing...</pre>`);
following.sort((a, b) => ((sizes[b] ?? 0) - (sizes[a] ?? 0)));
following.sort((a, b) => (sizes[b] ?? 0) - (sizes[a] ?? 0));
for (let id of following) {
tree += `<li><a href="/~core/ssb/#${id}">${escape(about[id]?.name ?? id)}</a> ${niceSize(sizes[id] ?? 0)}</li>\n`;
}
await app.setDocument('<!DOCTYPE html>\n<html>\n<body style="color: #fff"><h1>Following</h1>\n<ul>' + tree + '</ul>\n</body>\n</html>');
await app.setDocument(
'<!DOCTYPE html>\n<html>\n<body style="color: #fff"><h1>Following</h1>\n<ul>' +
tree +
'</ul>\n</body>\n</html>'
);
}
main();
main();

View File

@ -1,5 +1,5 @@
{
"type": "tildefriends-app",
"emoji": "🗺",
"previous": "&0XSp+xdQwVtQ88bXzvWdH15Ex63hv5zUKTa4zx7HBGM=.sha256"
}
"type": "tildefriends-app",
"emoji": "🗺",
"previous": "&0XSp+xdQwVtQ88bXzvWdH15Ex63hv5zUKTa4zx7HBGM=.sha256"
}

View File

@ -46,7 +46,7 @@ tfrpc.register(async function query(sql, args) {
return result;
});
tfrpc.register(async function store_blob(blob) {
if (typeof(blob) == 'string') {
if (typeof blob == 'string') {
blob = utf8Encode(blob);
}
if (Array.isArray(blob)) {
@ -71,10 +71,15 @@ async function main() {
let shared_db = await shared_database('state');
attempt = await shared_db.get(core.user.credentials.session.name);
}
app.setDocument(utf8Decode(getFile('index.html')).replace('${data}', JSON.stringify({
attempt: attempt,
state: core.user?.credentials?.session?.name,
})));
app.setDocument(
utf8Decode(getFile('index.html')).replace(
'${data}',
JSON.stringify({
attempt: attempt,
state: core.user?.credentials?.session?.name,
})
)
);
}
main();
main();

View File

@ -17,7 +17,7 @@ function xml_parse(xml) {
let tag = xml.substring(tag_begin, i).trim();
if (tag.startsWith('?') && tag.endsWith('?')) {
/* Ignore directives. */
} else if (tag.startsWith('/')) {
} else if (tag.startsWith('/')) {
path.pop();
} else {
let parts = tag.split(' ');
@ -63,7 +63,10 @@ export function gpx_parse(xml) {
for (let trkseg of xml_each(trk, 'trkseg')) {
let segment = [];
for (let trkpt of xml_each(trkseg, 'trkpt')) {
segment.push({lat: parseFloat(trkpt.attributes.lat), lon: parseFloat(trkpt.attributes.lon)});
segment.push({
lat: parseFloat(trkpt.attributes.lat),
lon: parseFloat(trkpt.attributes.lon),
});
}
result.segments.push(segment);
}
@ -78,4 +81,4 @@ export function gpx_parse(xml) {
}
}
return result;
}
}

View File

@ -18,4 +18,4 @@ async function main() {
status_code: 307,
});
}
main();
main();

View File

@ -1,14 +1,26 @@
<!DOCTYPE html>
<!doctype html>
<html style="width: 100%; height: 100%; margin: 0; padding: 0">
<head>
<script>window.litDisableBundleWarning = true;</script>
<script>
window.litDisableBundleWarning = true;
</script>
<script>
let g_data = ${data};
</script>
<script src="script.js" type="module"></script>
<script src="leaflet.js"></script>
</head>
<body style="color: #fff; display: flex; flex-flow: column; height: 100%; width: 100%; margin: 0; padding: 0">
<body
style="
color: #fff;
display: flex;
flex-flow: column;
height: 100%;
width: 100%;
margin: 0;
padding: 0;
"
>
<gg-app style="width: 100%; height: 100%" id="ggapp"></gg-app>
</body>
</html>
</html>

View File

@ -10,24 +10,24 @@
var polyline = {};
function py2_round(value) {
// Google's polyline algorithm uses the same rounding strategy as Python 2, which is different from JS for negative values
return Math.floor(Math.abs(value) + 0.5) * (value >= 0 ? 1 : -1);
// Google's polyline algorithm uses the same rounding strategy as Python 2, which is different from JS for negative values
return Math.floor(Math.abs(value) + 0.5) * (value >= 0 ? 1 : -1);
}
function encode(current, previous, factor) {
current = py2_round(current * factor);
previous = py2_round(previous * factor);
var coordinate = (current - previous) * 2;
if (coordinate < 0) {
coordinate = -coordinate - 1
}
var output = '';
while (coordinate >= 0x20) {
output += String.fromCharCode((0x20 | (coordinate & 0x1f)) + 63);
coordinate /= 32;
}
output += String.fromCharCode((coordinate | 0) + 63);
return output;
current = py2_round(current * factor);
previous = py2_round(previous * factor);
var coordinate = (current - previous) * 2;
if (coordinate < 0) {
coordinate = -coordinate - 1;
}
var output = '';
while (coordinate >= 0x20) {
output += String.fromCharCode((0x20 | (coordinate & 0x1f)) + 63);
coordinate /= 32;
}
output += String.fromCharCode((coordinate | 0) + 63);
return output;
}
/**
@ -41,54 +41,53 @@ function encode(current, previous, factor) {
*
* @see https://github.com/Project-OSRM/osrm-frontend/blob/master/WebContent/routing/OSRM.RoutingGeometry.js
*/
polyline.decode = function(str, precision) {
var index = 0,
lat = 0,
lng = 0,
coordinates = [],
shift = 0,
result = 0,
byte = null,
latitude_change,
longitude_change,
factor = Math.pow(10, Number.isInteger(precision) ? precision : 5);
polyline.decode = function (str, precision) {
var index = 0,
lat = 0,
lng = 0,
coordinates = [],
shift = 0,
result = 0,
byte = null,
latitude_change,
longitude_change,
factor = Math.pow(10, Number.isInteger(precision) ? precision : 5);
// Coordinates have variable length when encoded, so just keep
// track of whether we've hit the end of the string. In each
// loop iteration, a single coordinate is decoded.
while (index < str.length) {
// Coordinates have variable length when encoded, so just keep
// track of whether we've hit the end of the string. In each
// loop iteration, a single coordinate is decoded.
while (index < str.length) {
// Reset shift, result, and byte
byte = null;
shift = 1;
result = 0;
// Reset shift, result, and byte
byte = null;
shift = 1;
result = 0;
do {
byte = str.charCodeAt(index++) - 63;
result += (byte & 0x1f) * shift;
shift *= 32;
} while (byte >= 0x20);
do {
byte = str.charCodeAt(index++) - 63;
result += (byte & 0x1f) * shift;
shift *= 32;
} while (byte >= 0x20);
latitude_change = result & 1 ? (-result - 1) / 2 : result / 2;
latitude_change = (result & 1) ? ((-result - 1) / 2) : (result / 2);
shift = 1;
result = 0;
shift = 1;
result = 0;
do {
byte = str.charCodeAt(index++) - 63;
result += (byte & 0x1f) * shift;
shift *= 32;
} while (byte >= 0x20);
do {
byte = str.charCodeAt(index++) - 63;
result += (byte & 0x1f) * shift;
shift *= 32;
} while (byte >= 0x20);
longitude_change = result & 1 ? (-result - 1) / 2 : result / 2;
longitude_change = (result & 1) ? ((-result - 1) / 2) : (result / 2);
lat += latitude_change;
lng += longitude_change;
lat += latitude_change;
lng += longitude_change;
coordinates.push([lat / factor, lng / factor]);
}
coordinates.push([lat / factor, lng / factor]);
}
return coordinates;
return coordinates;
};
/**
@ -98,28 +97,33 @@ polyline.decode = function(str, precision) {
* @param {Number} precision
* @returns {String}
*/
polyline.encode = function(coordinates, precision) {
if (!coordinates.length) { return ''; }
polyline.encode = function (coordinates, precision) {
if (!coordinates.length) {
return '';
}
var factor = Math.pow(10, Number.isInteger(precision) ? precision : 5),
output = encode(coordinates[0][0], 0, factor) + encode(coordinates[0][1], 0, factor);
var factor = Math.pow(10, Number.isInteger(precision) ? precision : 5),
output =
encode(coordinates[0][0], 0, factor) +
encode(coordinates[0][1], 0, factor);
for (var i = 1; i < coordinates.length; i++) {
var a = coordinates[i], b = coordinates[i - 1];
output += encode(a[0], b[0], factor);
output += encode(a[1], b[1], factor);
}
for (var i = 1; i < coordinates.length; i++) {
var a = coordinates[i],
b = coordinates[i - 1];
output += encode(a[0], b[0], factor);
output += encode(a[1], b[1], factor);
}
return output;
return output;
};
function flipped(coords) {
var flipped = [];
for (var i = 0; i < coords.length; i++) {
var coord = coords[i].slice();
flipped.push([coord[1], coord[0]]);
}
return flipped;
var flipped = [];
for (var i = 0; i < coords.length; i++) {
var coord = coords[i].slice();
flipped.push([coord[1], coord[0]]);
}
return flipped;
}
/**
@ -129,14 +133,14 @@ function flipped(coords) {
* @param {Number} precision
* @returns {String}
*/
polyline.fromGeoJSON = function(geojson, precision) {
if (geojson && geojson.type === 'Feature') {
geojson = geojson.geometry;
}
if (!geojson || geojson.type !== 'LineString') {
throw new Error('Input must be a GeoJSON LineString');
}
return polyline.encode(flipped(geojson.coordinates), precision);
polyline.fromGeoJSON = function (geojson, precision) {
if (geojson && geojson.type === 'Feature') {
geojson = geojson.geometry;
}
if (!geojson || geojson.type !== 'LineString') {
throw new Error('Input must be a GeoJSON LineString');
}
return polyline.encode(flipped(geojson.coordinates), precision);
};
/**
@ -146,13 +150,13 @@ polyline.fromGeoJSON = function(geojson, precision) {
* @param {Number} precision
* @returns {Object}
*/
polyline.toGeoJSON = function(str, precision) {
var coords = polyline.decode(str, precision);
return {
type: 'LineString',
coordinates: flipped(coords)
};
polyline.toGeoJSON = function (str, precision) {
var coords = polyline.decode(str, precision);
return {
type: 'LineString',
coordinates: flipped(coords),
};
};
let polyline_decode = polyline.decode;
export { polyline_decode as decode };
export {polyline_decode as decode};

View File

@ -1,4 +1,11 @@
import {LitElement, html, unsafeHTML, css, guard, until} from './lit-all.min.js';
import {
LitElement,
html,
unsafeHTML,
css,
guard,
until,
} from './lit-all.min.js';
import * as tfrpc from '/static/tfrpc.js';
import * as polyline from './polyline.js';
import {gpx_parse} from './gpx.js';
@ -56,7 +63,7 @@ class GgAppElement extends LitElement {
this.focus = undefined;
this.status = undefined;
this.tab = 'map';
this.load().catch(function(e) {
this.load().catch(function (e) {
console.log('load error', e);
});
this.to_build = '🏠';
@ -65,9 +72,12 @@ class GgAppElement extends LitElement {
async load() {
console.log('load');
let emojis = await (await fetch('emojis.json')).json();
emojis = Object.values(emojis).map(x => Object.values(x)).flat();
emojis = Object.values(emojis)
.map((x) => Object.values(x))
.flat();
let today = new Date();
let date_index = today.getYear() * 356 + today.getMonth() * 31 + today.getDate();
let date_index =
today.getYear() * 356 + today.getMonth() * 31 + today.getDate();
this.emoji_of_the_day = emojis[(date_index * 123457) % emojis.length];
this.user = await tfrpc.rpc.getUser();
this.url = (await tfrpc.rpc.url()).split('?')[0];
@ -109,7 +119,8 @@ class GgAppElement extends LitElement {
async get_activities_from_ssb() {
this.status = {text: 'loading activities'};
this.loaded_activities = [];
let rows = await tfrpc.rpc.query(`
let rows = await tfrpc.rpc.query(
`
SELECT messages.author, json_extract(mention.value, '$.link') AS blob_id
FROM messages_fts('"gg-activity"')
JOIN messages ON messages.rowid = messages_fts.rowid,
@ -117,10 +128,15 @@ class GgAppElement extends LitElement {
WHERE json_extract(messages.content, '$.type') = 'gg-activity' AND
json_extract(mention.value, '$.name') = 'activity_data'
ORDER BY messages.timestamp DESC
`, []);
`,
[]
);
this.status = {text: 'loading activity data'};
let authors = rows.map(x => x.author);
let blobs = await this.promise_all(rows.map(x => tfrpc.rpc.get_blob(x.blob_id)), 8);
let authors = rows.map((x) => x.author);
let blobs = await this.promise_all(
rows.map((x) => tfrpc.rpc.get_blob(x.blob_id)),
8
);
this.status = {text: 'processing activity data'};
for (let [index, blob] of blobs.entries()) {
let activity;
@ -135,13 +151,19 @@ class GgAppElement extends LitElement {
}
}
this.status = {text: 'calculating balance'};
rows = await tfrpc.rpc.query(`
rows = await tfrpc.rpc.query(
`
SELECT count(*) AS currency FROM messages WHERE author = ? AND json_extract(content, '$.type') = 'gg-activity'
`, [this.whoami]);
`,
[this.whoami]
);
let currency = rows[0].currency;
rows = await tfrpc.rpc.query(`
rows = await tfrpc.rpc.query(
`
SELECT SUM(json_extract(content, '$.cost')) AS cost FROM messages WHERE author = ? AND json_extract(content, '$.type') = 'gg-place'
`, [this.whoami]);
`,
[this.whoami]
);
let spent = rows[0].cost;
this.currency = currency - spent;
this.status = {text: 'getting placed emojis'};
@ -166,8 +188,11 @@ class GgAppElement extends LitElement {
}
async sync_activities() {
let ids = this.activities.map(x => `https://www.strava.com/activities/${x.id}`);
let missing = await tfrpc.rpc.query(`
let ids = this.activities.map(
(x) => `https://www.strava.com/activities/${x.id}`
);
let missing = await tfrpc.rpc.query(
`
WITH my_activities AS (
SELECT json_extract(mention.value, '$.link') AS url
FROM messages, json_each(messages.content, '$.mentions') AS mention
@ -178,17 +203,26 @@ class GgAppElement extends LitElement {
SELECT from_strava.value FROM json_each(?) AS from_strava
LEFT OUTER JOIN my_activities ON from_strava.value = my_activities.url
WHERE my_activities.url IS NULL
`, [this.whoami, JSON.stringify(ids)]);
`,
[this.whoami, JSON.stringify(ids)]
);
console.log('missing = ', missing);
for (let [index, row] of missing.entries()) {
this.status = {text: 'syncing from strava', value: index, max: missing.length};
this.status = {
text: 'syncing from strava',
value: index,
max: missing.length,
};
let url = row.value;
let id = url.match(/.*\/(\d+)/)[1];
let response = await fetch(`https://www.strava.com/api/v3/activities/${id}`, {
headers: {
'Authorization': `Bearer ${this.strava.access_token}`,
},
});
let response = await fetch(
`https://www.strava.com/api/v3/activities/${id}`,
{
headers: {
Authorization: `Bearer ${this.strava.access_token}`,
},
}
);
let activity = await response.json();
let blob_id = await tfrpc.rpc.store_blob(JSON.stringify(activity));
let message = {
@ -201,7 +235,7 @@ class GgAppElement extends LitElement {
{
link: blob_id,
name: 'activity_data',
}
},
],
};
await tfrpc.rpc.appendMessage(this.whoami, message);
@ -215,13 +249,20 @@ class GgAppElement extends LitElement {
return;
}
let ids = await tfrpc.rpc.getIdentities();
let players = ids.length ? (await tfrpc.rpc.query(`
let players = ids.length
? (
await tfrpc.rpc.query(
`
SELECT author FROM messages JOIN json_each(?) ON messages.author = json_each.value
WHERE
json_extract(messages.content, '$.type') = 'gg-player' AND
</