Skip to content

Commit

Permalink
clean up typescript
Browse files Browse the repository at this point in the history
  • Loading branch information
Erudition committed Nov 20, 2023
1 parent fb6cbd3 commit a5e9b65
Show file tree
Hide file tree
Showing 2 changed files with 148 additions and 146 deletions.
39 changes: 21 additions & 18 deletions www/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ async function installTaskPorts() {
registerNotificationTaskPorts();
TaskPort.register("changePassphrase", () => getPassphrase(true));
TaskPort.register("requestNotificationPermission", LocalNotifications.requestPermissions)
TaskPort.register("ionInputSetFocus", (id : String) => document?.getElementById(id).setFocus())
TaskPort.register("ionInputSetFocus", (id : string) => document?.getElementById(id)!.setFocus())
TaskPort.register("dialogPrompt", Dialog.prompt)
}

Expand Down Expand Up @@ -158,7 +158,7 @@ async function getPassphrase(shouldReset) {
const notPreviouslySet = storedPassphrase == null || storedPassphrase == ""

if (notPreviouslySet || shouldReset) {
const fallbackPassphrase = notPreviouslySet ? ("tester" + Math.floor(Math.random()*1000)) : storedPassphrase
const fallbackPassphrase = storedPassphrase ? ("tester" + Math.floor(Math.random()*1000)) : storedPassphrase

const { value, cancelled } = await Dialog.prompt({
title: 'New Device',
Expand Down Expand Up @@ -212,22 +212,25 @@ async function attachOrbit(elmApp) {

async function attachODDManual(elmApp) {
const oddIntegration = await import('./scripts/odd')
let retrievedRon = await oddIntegration.readData();
if (retrievedRon) {
elmApp.ports.incomingRon.send(retrievedRon)
} else {
console.error("Couldn't retrieve RON from WNFS", retrievedRon)
}
// SET STORAGE
elmApp.ports.setStorage.subscribe(async function(state) {
if (state.trim() != "")
{
console.log("Adding state to WNFS", state);
const hash = oddIntegration.saveData(state);
} else {
console.error("Tried to save empty RON data...")
}
});
//const program = oddIntegration.init();


// let retrievedRon = await oddIntegration.readData(program, program!.session);
// if (retrievedRon) {
// elmApp.ports.incomingRon.send(retrievedRon)
// } else {
// console.error("Couldn't retrieve RON from WNFS", retrievedRon)
// }
// // SET STORAGE
// elmApp.ports.setStorage.subscribe(async function(state) {
// if (state.trim() != "")
// {
// console.log("Adding state to WNFS", state);
// const hash = oddIntegration.saveData(state);
// } else {
// console.error("Tried to save empty RON data...")
// }
// });
}

async function attachODDElmLibrary() {
Expand Down
255 changes: 127 additions & 128 deletions www/scripts/odd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,164 +3,163 @@ import * as odd from '@oddjs/odd'

const appInfo = { creator: "Minder", name: "Minder" }

const program = await odd.program({
namespace: appInfo,
debug: true, //lets us access window.__odd[odd.namespace(appInfo)]
fileSystem: { loadImmediately: true }

}).catch(error => {
switch (error) {
case odd.ProgramError.InsecureContext:
// ODD requires HTTPS
break;
case odd.ProgramError.UnsupportedBrowser:
// Browsers must support IndexedDB
break;
}
})

program!.on('session:create', ({ session }) => {
console.log('A session was created', session)
})

program!.on('session:destroy', ({ username }) => {
console.log('A session was destroyed for username', username)
})
export function init() : odd.Program | string {
let problem = "Unforeseen error initializing ODD"

let session = program!.session

if (session) {
console.log("You have a WNFS session! \n Username:" + session.username + "\n Type: "+ session.type + "\n Filesystem Root DID: " + session.fs?.account.rootDID)
} else {
let chosenUsername = prompt("Enter a new username")
let chosenEmail = prompt("Enter a new email")
if (chosenUsername && chosenEmail) {
registerUser(chosenUsername, chosenEmail);
}
const program = odd.program({
namespace: appInfo,
debug: true, //lets us access window.__odd[odd.namespace(appInfo)]
fileSystem: { loadImmediately: true }

}).catch(error => {
switch (error) {
case odd.ProgramError.InsecureContext:
// ODD requires HTTPS
problem = "Insecure context"
break;
case odd.ProgramError.UnsupportedBrowser:
// Browsers must support IndexedDB
problem = "Unsupported browser"
break;
}
}).then(program => {
if (program) {
// happy path
program.on('session:create', ({ session }) => {
console.log('A session was created', session)
})

program.on('session:destroy', ({ username }) => {
console.log('A session was destroyed for username', username)
})

let session = program.session

if (session) {
console.log("You have a WNFS session! \n Username:" + session.username + "\n Type: "+ session.type + "\n Filesystem Root DID: " + session.fs?.account.rootDID)
} else {
let chosenUsername = prompt("Enter a new username")
let chosenEmail = prompt("Enter a new email")
if (chosenUsername && chosenEmail) {
registerUser(program, chosenUsername, chosenEmail);
}
}
return program;
}
})
return problem;

}


export async function linkNewDeviceWithSession(session: odd.Session) {
if (program)
{
const producer = await program!.auth.accountProducer(session.username)
export async function linkNewDeviceWithSession(program: odd.Program, session: odd.Session) {
const producer = await program!.auth.accountProducer(session.username)

producer.on("challenge", challenge => {
// Either show `challenge.pin` or have the user input a PIN and see if they're equal.
if (window.confirm("For security, only choose OK if the PIN matches exactly on the other device.\nPIN: " + challenge.pin))
challenge.confirmPin()
else challenge.rejectPin()
})
producer.on("challenge", challenge => {
// Either show `challenge.pin` or have the user input a PIN and see if they're equal.
if (window.confirm("For security, only choose OK if the PIN matches exactly on the other device.\nPIN: " + challenge.pin))
challenge.confirmPin()
else challenge.rejectPin()
})

producer.on("link", ({ approved }) => {
if (approved) console.log("Linked new device successfully")
})

producer.on("link", ({ approved }) => {
if (approved) console.log("Linked new device successfully")
})
} else {
console.error("Tried to linkNewDeviceWithSession but there was no program. Program is", program)
}
}

export async function linkNewDeviceWithoutSession(username: string) {
if (program)
{
const consumer = await program.auth.accountConsumer(username)
export async function linkNewDeviceWithoutSession(program: odd.Program, username: string) {
const consumer = await program.auth.accountConsumer(username)

consumer.on("challenge", ({ pin }) => {
consumer.on("challenge", ({ pin }) => {
alert("Match this PIN on the other device. \nPIN: " + pin)
})
})

consumer.on("link", async ({ approved, username }) => {
consumer.on("link", async ({ approved, username }) => {
if (approved) {
console.log(`Successfully authenticated as ${username}`)
session = await program.auth.session()
console.log(`Successfully authenticated as ${username}`)
return await program.auth.session()
}
})
} else {
console.error("Tried to linkNewDeviceWithSession but there was no program. Program is", program)
return null;
}
})

}

export async function registerUser(username: string, email: string) {
if (program)
{
if (!program.session)
{
// Check if username is valid and available
const valid = await program.auth.isUsernameValid(username)
const available = await program.auth.isUsernameAvailable(username)

if (valid && available)
{
// Register the user
const { success } = await program.auth.register({ username, email })

// Create a session on success
const session = success ? await program.auth.session() : null

}
} else
{
console.error("Tried to registerUser but there was already an existing session.", session)
}
} else
{
console.error("Tried to registerUser but there was no program. Program is", program)
}
export async function registerUser(program: odd.Program, username: string, email: string) {

if (!program.session)
{
// Check if username is valid and available
const valid = await program.auth.isUsernameValid(username)
const available = await program.auth.isUsernameAvailable(username)

if (valid && available)
{
// Register the user
const { success } = await program.auth.register({ username, email })

// Create a session on success
const session = success ? await program.auth.session() : null

}
} else
{
console.error("Tried to registerUser but there was already an existing session.", !program.session)
}

}

export async function saveData(ron : string) {
if (program && session && session.fs)
export async function saveData(program: odd.Program, session: odd.Session, ron : string) {
if (session.fs)
{
// After retrieving a session or loading the file system manually
const fs = session.fs // or program.loadFileSystem(username)
// After retrieving a session or loading the file system manually
const fs = session.fs // or program.loadFileSystem(username)

// List the user's public files
await fs.ls(odd.path.directory("public"))
// List the user's public files
await fs.ls(odd.path.directory("public"))

// List the user's private files that belong to a specific app
await fs.ls(odd.path.appData(appInfo))
// List the user's private files that belong to a specific app
await fs.ls(odd.path.appData(appInfo))

// Create a sub directory and write to a file
await fs.write(
odd.path.appData(appInfo, odd.path.file("RON", "profile.ron")),
new TextEncoder().encode(ron)
)
// Create a sub directory and write to a file
await fs.write(
odd.path.appData(appInfo, odd.path.file("RON", "profile.ron")),
new TextEncoder().encode(ron)
)

// Persist changes and announce them to your other devices
await fs.publish()
// Persist changes and announce them to your other devices
await fs.publish()
} else
{
console.error("Tried to saveData but program or session or fs was missing. Program is", program, "session is", session, "fs is", session!.fs)
console.error("Tried to saveData but fs was missing. Program is", program, "session is", session, "fs is", session!.fs)
}
}


export async function readData() {
if (program && session && session.fs)
export async function readData(program: odd.Program, session: odd.Session) {
if (session.fs)
{
let fileExists = await session.fs.exists( odd.path.appData(appInfo, odd.path.file("RON", "profile.ron")) )
let content = "";

if (fileExists) {
console.log("minder path exists." )
// Read from the file
content = new TextDecoder().decode(
await session.fs.read(
odd.path.appData(appInfo, odd.path.file("RON", "profile.ron"))
)
)
} else {
await session?.fs!.write(
odd.path.appData(appInfo, odd.path.file("RON", "profile.ron")),
new TextEncoder().encode("start;")
)
}

return content;
let fileExists = await session.fs.exists( odd.path.appData(appInfo, odd.path.file("RON", "profile.ron")) )
let content = "";

if (fileExists) {
console.log("minder path exists." )
// Read from the file
content = new TextDecoder().decode(
await session.fs.read(
odd.path.appData(appInfo, odd.path.file("RON", "profile.ron"))
)
)
} else {
await session?.fs!.write(
odd.path.appData(appInfo, odd.path.file("RON", "profile.ron")),
new TextEncoder().encode("start;")
)
}

return content;
} else
{
console.error("Tried to readData but program or session or fs was missing. Program is", program, "session is", session, "fs is", session!.fs)
return null;
console.error("Tried to readData but fs was missing. Program is", program, "session is", session, "fs is", session!.fs)
return null;
}
}

0 comments on commit a5e9b65

Please sign in to comment.