Skip to content

Commit

Permalink
TAB-481 savepoint
Browse files Browse the repository at this point in the history
  • Loading branch information
evandor committed Jan 11, 2024
1 parent 8dd4b66 commit 552da41
Show file tree
Hide file tree
Showing 6 changed files with 109 additions and 48 deletions.
3 changes: 3 additions & 0 deletions src/boot/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ const SHARING_AVATAR_IDENT = 'sharing.avatar';
const SHARING_MQTT_IDENT = 'sharing.mqttUrl';
const SHARING_INSTALLATION = 'sharing.installation'

const SYNC_TYPE = "sync.type"

const SYNC_GITLAB_URL = "sync.gitlab.url"
const SYNC_GITLAB_TOKEN = "sync.gitlab.token"

Expand All @@ -50,6 +52,7 @@ export {
SHARING_AVATAR_IDENT,
SHARING_MQTT_IDENT,
SHARING_INSTALLATION,
SYNC_TYPE,
SYNC_GITLAB_URL,
SYNC_GITLAB_TOKEN,
SYNC_GITHUB_URL,
Expand Down
4 changes: 2 additions & 2 deletions src/pages/SidePanelPage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@
<template v-slot:title v-else>
<div class="text-subtitle1 text-black">
{{ toolbarTitle(tabsets as Tabset[]) }}
<q-icon v-if="LocalStorage.getItem('sync.type') as SyncType === SyncType.GITHUB"
<q-icon v-if="LocalStorage.getItem(SYNC_TYPE) as SyncType === SyncType.GITHUB"
class="q-ml-none" name="sync" size="12px">
<q-tooltip class="tooltip-small">Tabsets is synced via git</q-tooltip>
</q-icon>
Expand Down Expand Up @@ -284,7 +284,7 @@ import {useVOnboarding, VOnboardingStep, VOnboardingWrapper} from 'v-onboarding'
import {FirebaseCall} from "src/services/firebase/FirebaseCall";
import getScrollTarget = scroll.getScrollTarget;
import InfoMessageWidget from "components/widgets/InfoMessageWidget.vue";
import {TITLE_IDENT} from "boot/constants";
import {SYNC_TYPE, TITLE_IDENT} from "boot/constants";
import {collection, getDoc, doc, onSnapshot, setDoc, addDoc} from "firebase/firestore";
import {firestore} from "boot/firebase";
Expand Down
40 changes: 29 additions & 11 deletions src/pages/helper/SubscriptionBexSettings.vue
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@

<div class="row items-baseline q-ma-md q-gutter-lg">

<div class="col-3">
Authorize to subscribe or check your subscriptions
</div>
<div class="col-5">
<q-btn label="GitHub" @click="authorizeWith(githubAuthProvider)"/>
</div>
<div class="col">
Authorized as: {{ userCredentials?.user.email || '---' }}
</div>
<!-- <div class="col-3">-->
<!-- Authorize to subscribe or check your subscriptions-->
<!-- </div>-->
<!-- <div class="col-5">-->
<!-- <q-btn label="GitHub" @click="authorizeWith(githubAuthProvider)"/>-->
<!-- </div>-->
<!-- <div class="col">-->
<!-- Authorized as: {{ userCredentials?.user.email || '-&#45;&#45;' }}-->
<!-- </div>-->

<template v-if="!subscription">
<div class="col-3">
Expand Down Expand Up @@ -75,7 +75,7 @@ import {SUBSCRIPTION_ID_IDENT} from "boot/constants";
import {FirebaseCall} from "src/services/firebase/FirebaseCall";
import {getAuth, onAuthStateChanged} from "firebase/auth";
import {firebaseApp, githubAuthProvider, firestore} from "boot/firebase";
import {createUserWithEmailAndPassword, signInWithPopup, UserCredential} from "firebase/auth";
import {createUserWithEmailAndPassword, signInWithPopup, signInWithRedirect,signInWithEmailLink,sendSignInLinkToEmail, signInWithCredential, UserCredential} from "firebase/auth";
import {collection, setDoc, doc} from "firebase/firestore";
const subscription = ref<string>(LocalStorage.getItem(SUBSCRIPTION_ID_IDENT) as string || '')
Expand Down Expand Up @@ -108,7 +108,25 @@ const authorizeWith = async (githubAuthProvider:any) => {
const auth = getAuth(firebaseApp);
console.log("auth", auth)
//createUserWithEmailAndPassword(auth, "email", "password")
const credentials: UserCredential = await signInWithPopup(auth, githubAuthProvider)
//const credentials: UserCredential = await signInWithPopup(auth, githubAuthProvider)
const credentials: UserCredential = await signInWithCredential(auth, githubAuthProvider)
//const credentials: UserCredential = await signInWithRedirect(auth, githubAuthProvider)
// const actionCodeSettings = {
// url: 'https://www.example.com/[email protected]',
// iOS: {
// bundleId: 'com.example.ios'
// },
// android: {
// packageName: 'com.example.android',
// installApp: true,
// minimumVersion: '12'
// },
// handleCodeInApp: true
// };
// await sendSignInLinkToEmail(auth, '[email protected]', actionCodeSettings);
//const credentials: UserCredential = await signInWithEmailLink(auth, "[email protected]")
console.log("userCredentials", credentials)
console.log("userCredentials", {...credentials.user})
userCredentials.value = credentials
Expand Down
49 changes: 33 additions & 16 deletions src/pages/helper/SyncingSettings.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<template>
<div class="q-pa-md q-gutter-sm">
<q-banner rounded class="bg-grey-1 text-primary" style="border: 1px solid orange">
<div class="text-body1">Experimental: Sync your tabsets with git (or couchdb)</div>
<div class="text-body1">Experimental: Synchronize your tabsets across computers and browsers</div>
</q-banner>

<div class="row items-baseline q-ma-md q-gutter-lg">
Expand Down Expand Up @@ -42,10 +42,13 @@
<div class="col-7 text-caption" v-if="tempSyncOption === SyncType.COUCHDB">
Sync your tabsets across browsers and computers via a database (not yet supported)
</div>
<div class="col-7 text-caption" v-if="tempSyncOption === SyncType.MANAGED_COUCHDB || tempSyncOption === SyncType.MANAGED_GIT">
Use Managed Synchronisation to access your tabsets from anyway using a paid service (not yet supported)
<div class="col-7 text-caption"
v-if="tempSyncOption === SyncType.MANAGED_COUCHDB || tempSyncOption === SyncType.MANAGED_GIT">
Use Managed Synchronisation to access your tabsets from anywhere for a small fee (not yet supported)
<div class="q-mt-md" v-if="subscription === undefined">
If you want to use this, create a <span class="cursor-pointer text-blue-8" @click.stop="emits('wasClicked',{tab: 'subscription'})">subscription</span> and
If you want to use this, create a <span class="cursor-pointer text-blue-8"
@click.stop="emits('wasClicked',{tab: 'subscription'})">subscription</span>
and
come back here.
</div>
</div>
Expand Down Expand Up @@ -182,14 +185,17 @@
<div class="col text-right"></div>
</template>

<template v-if="tempSyncOption === SyncType.MANAGED_GIT">
<div class="col-3"></div>
<template v-if="tempSyncOption === SyncType.MANAGED_GIT && subscription">
<div clas="col-3">&nbsp;</div>
<div clas="col-7">You have added a subscription; let's try to setup your account</div>
<div clas="col">&nbsp;</div>

<div class="col-3">&nbsp;</div>
<div class="col-7">
<q-btn
label="Test Subscription" @click="testSubscription()"/>
<q-btn label="Check Setup" @click="checkManagedGitSetup()"/>
<span class="q-ml-md"> {{ testResult }}</span>
</div>
<div class="col text-right"></div>
<div class="col text-right">&nbsp;</div>
</template>

<template v-if="startSyncMessage(SyncType.GITHUB)">
Expand Down Expand Up @@ -301,7 +307,7 @@ import {
SYNC_GITHUB_TOKEN,
SYNC_GITHUB_URL,
SYNC_GITLAB_TOKEN,
SYNC_GITLAB_URL
SYNC_GITLAB_URL, SYNC_TYPE
} from "boot/constants";
import GitPersistentService from "src/services/persistence/GitPersistentService";
import {FirebaseCall} from "src/services/firebase/FirebaseCall";
Expand All @@ -311,7 +317,7 @@ import {useTabsetService} from "src/services/TabsetService2";
const emits = defineEmits(['wasClicked'])
const syncType = ref<string | undefined>(undefined)
const tempSyncOption = ref<SyncType>(LocalStorage.getItem('sync.type') as SyncType || SyncType.NONE)
const tempSyncOption = ref<SyncType>(LocalStorage.getItem(SYNC_TYPE) as SyncType || SyncType.NONE)
const gitlabRepoToken = ref<string>(LocalStorage.getItem(SYNC_GITLAB_TOKEN) as string || '')
const gitlabRepoUrl = ref<string>(LocalStorage.getItem(SYNC_GITLAB_URL) as string || '')
Expand All @@ -332,9 +338,9 @@ const syncOptions = [
{label: 'No Syncing', value: SyncType.NONE, desc: ""},
{label: 'Syncing via github repository', value: SyncType.GITHUB},
// {label: 'Syncing via gitlab repository', value: SyncType.GITLAB},
{label: 'Syncing via database', value: SyncType.COUCHDB},
// {label: 'Syncing via database', value: SyncType.COUCHDB},
{label: 'Managed Git Synchronisation', value: SyncType.MANAGED_GIT},
{label: 'Managed Database Synchronisation', value: SyncType.MANAGED_COUCHDB}
// {label: 'Managed Database Synchronisation', value: SyncType.MANAGED_COUCHDB}
]
function checkAndUpdate(val: string, ident: string) {
Expand All @@ -359,7 +365,7 @@ watchEffect(() => {
})
watchEffect(() => {
syncType.value = LocalStorage.getItem('sync.type') as SyncType
syncType.value = LocalStorage.getItem(SYNC_TYPE) as SyncType
})
Expand Down Expand Up @@ -393,8 +399,8 @@ const testDbConnection = async () => {
}
}
const startGitSyncing = () => LocalStorage.set("sync.type", tempSyncOption.value)
const stopGitSyncing = () => LocalStorage.set("sync.type", SyncType.NONE)
const startGitSyncing = () => LocalStorage.set(SYNC_TYPE, tempSyncOption.value)
const stopGitSyncing = () => LocalStorage.set(SYNC_TYPE, SyncType.NONE)
const startSyncMessage = (targetType: SyncType) => testResult.value === 'success' &&
(!syncType.value || syncType.value === SyncType.NONE) &&
Expand All @@ -413,4 +419,15 @@ const testSubscription = () => {
useTabsetService().reloadTabset(newTabset.id)
})
}
const checkManagedGitSetup = async () => {
try {
const response = await FirebaseCall.post("/subscriptions", {"userId": "abc"})
console.log("response", response)
testResult.value = "success"
} catch (err) {
console.log("got error", err)
}
}
</script>
8 changes: 4 additions & 4 deletions src/services/AppService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {FeatureIdent} from "src/models/AppFeature";
import {useMessagesStore} from "src/stores/messagesStore";
import {SyncType, useAppStore} from "stores/appStore";
import GitPersistentService from "src/services/persistence/GitPersistentService";
import {SYNC_GITHUB_URL} from "boot/constants";
import {SYNC_GITHUB_URL, SYNC_TYPE} from "boot/constants";

class AppService {

Expand Down Expand Up @@ -60,9 +60,9 @@ class AppService {
const localStorage = useQuasar().localStorage

// sync features
const syncType = LocalStorage.getItem("sync.type") as SyncType || SyncType.NONE
const syncType = LocalStorage.getItem(SYNC_TYPE) as SyncType || SyncType.NONE
const syncUrl = LocalStorage.getItem(SYNC_GITHUB_URL) as string
const dbOrGitDb = syncType && syncType === SyncType.GITHUB && syncUrl ? useDB(undefined).gitDb : useDB(undefined).db
const dbOrGitDb = syncType && (syncType === SyncType.GITHUB || syncType === SyncType.MANAGED_GIT) && syncUrl ? useDB(undefined).gitDb : useDB(undefined).db
console.log("checking sync config:", syncType, syncUrl, dbOrGitDb)

// init db
Expand All @@ -76,7 +76,7 @@ class AppService {

tabsetService.setLocalStorage(localStorage)

GitPersistentService.init(syncUrl)
GitPersistentService.init(syncType, syncUrl)
.then((gitInitResult:string) => {
console.log("gitInitResult", gitInitResult)
spacesStore.initialize(dbOrGitDb)
Expand Down
53 changes: 38 additions & 15 deletions src/services/persistence/GitPersistentService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,13 @@ async function createDir(...segments: string[]) {
}
}

async function push(dir: string) {
async function push(dir: string, proxy: string) {
let pushResult = await git.push({
fs,
http,
dir,
remote: 'origin',
corsProxy: 'https://cors.isomorphic-git.org',
corsProxy: proxy,
ref: 'main',
onAuth: () => ({username: LocalStorage.getItem(SYNC_GITHUB_TOKEN) as string || '---'}),
})
Expand All @@ -62,29 +62,39 @@ async function push(dir: string) {
class GitPersistenceService implements PersistenceService {
private db: IDBPDatabase = null as unknown as IDBPDatabase
private readonly _dir = "/tabsets";
private genericCorsProxy = 'https://cors.isomorphic-git.org'
private tabsetsCorsProxy = 'https://git.tabsets.net'

// TODO
async init(url: string | undefined) {
private useProxy = this.genericCorsProxy

async init(syncType: SyncType, url: string | undefined) {
if (url) {
if (LocalStorage.getItem("sync.type") as SyncType === SyncType.GITHUB) {
console.log("=== initializing git database ===", url)
this.db = await this.initDatabase(url)
if (syncType === SyncType.GITHUB) {
console.log("=== initializing github database ===", url)
this.db = await this.initDatabase(url, this.genericCorsProxy)
console.log("=== initializing git database: done ===")
useUiStore().dbReady = true
return Promise.resolve("done")
} else if (syncType === SyncType.MANAGED_GIT) {
console.log("=== initializing managed git ===", url)
this.db = await this.initDatabase(url, this.tabsetsCorsProxy)
console.log("=== initializing managed git done ===")
useUiStore().dbReady = true
return Promise.resolve("done")
}
}
return Promise.resolve("no url given")
}


private async initDatabase(url: string, dir: string = this._dir): Promise<any> {
private async initDatabase(url: string, proxy: string, dir: string = this._dir): Promise<any> {
window.fs = new LightningFS('fs')
window.pfs = window.fs.promises
console.debug("about to initialize git")
const useDir = dir + "-" + Md5.hashStr(url)
window.dir = useDir
console.log(useDir);
this.useProxy = proxy
try {
await pfs.mkdir(useDir);
} catch (err: any) {
Expand All @@ -102,15 +112,27 @@ class GitPersistenceService implements PersistenceService {
fs,
http,
dir: useDir,
corsProxy: 'https://cors.isomorphic-git.org',
//corsProxy: 'https://cors.isomorphic-git.org',
corsProxy: this.useProxy,
url: url,
ref: 'main',
singleBranch: true,
depth: 10,
//onProgress: (val:any) => (console.log("onProgress", val)),
//onMessage: (val:any) => (console.log("onMessage", val)),
onAuthSuccess: () => (console.log("auth: success")),
onAuthFailure: () => ("auth: failure"),
onAuthFailure: (url, auth) => {
//forgetSavedPassword(url)
if (confirm('Access was denied. Try again?')) {
auth = {
username: prompt('Enter username'),
password: prompt('Enter password'),
}
return auth
} else {
return { cancel: true }
}
},
onAuth: () => ({username: LocalStorage.getItem(SYNC_GITHUB_TOKEN) as string || '---'}),
}
console.log(`about to clone '${url}' into ${useDir}`, cloneDef)
Expand All @@ -132,7 +154,7 @@ class GitPersistenceService implements PersistenceService {

const remoteInfoDef = {
http,
corsProxy: "https://cors.isomorphic-git.org",
corsProxy: this.useProxy,
url: gitRepoUrl,
onAuthSuccess: () => {
console.log("auth: success")
Expand Down Expand Up @@ -210,6 +232,7 @@ class GitPersistenceService implements PersistenceService {
console.warn("err", err)
}
for (const t of tabsets) {
console.log("adding t", t)
useTabsStore().addTabset(t)
}

Expand Down Expand Up @@ -248,13 +271,13 @@ class GitPersistenceService implements PersistenceService {

console.log(sha)
//await push(this._dir);
await push(`${dir}`);
await push(`${dir}`, this.useProxy);
return Promise.resolve(undefined);
}

async deleteTabset(tabsetId: string): Promise<any> {
await pfs.rmdir(`${dir}/tabsets/${tabset.id}`)
await push(`${dir}`);
await push(`${dir}`, this.useProxy);
return Promise.resolve(undefined);
}

Expand Down Expand Up @@ -339,14 +362,14 @@ class GitPersistenceService implements PersistenceService {

console.log(sha)
//await push(this._dir);
await push(`${dir}`);
await push(`${dir}`, this.useProxy);
return Promise.resolve(undefined);
}

async deleteSpace(entityId: string) {
await pfs.rmdir(`${dir}/spaces/${entityId}`)
//await push(this._dir);
await push(`${dir}`);
await push(`${dir}`, this.useProxy);
return Promise.resolve(undefined);
}

Expand Down

0 comments on commit 552da41

Please sign in to comment.