Skip to content

Commit

Permalink
Migrate and drop old person database
Browse files Browse the repository at this point in the history
Signed-off-by: Jack Works <[email protected]>
  • Loading branch information
Jack-Works committed Jun 4, 2019
1 parent 3dd9215 commit 2bf4443
Show file tree
Hide file tree
Showing 11 changed files with 67 additions and 21 deletions.
3 changes: 2 additions & 1 deletion src/components/InjectedComponents/AddToKeyStore.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ import AsyncComponent from '../../utils/components/AsyncComponent'
import { AdditionalContent } from './AdditionalPostContent'
import Services from '../../extension/service'
import { geti18nString } from '../../utils/i18n'
import { PersonIdentifier } from '../../database/type'

interface Props {
provePost: string
postBy: string
postBy: PersonIdentifier
}
export function AddToKeyStore({ provePost, postBy }: Props) {
return (
Expand Down
5 changes: 3 additions & 2 deletions src/components/InjectedComponents/DecryptedPost.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { geti18nString } from '../../utils/i18n'
import { makeStyles } from '@material-ui/styles'
import { Link, Box } from '@material-ui/core'
import { Person } from '../../database'
import { PersonIdentifier } from '../../database/type'

interface DecryptPostSuccessProps {
data: { signatureVerifyResult: boolean; content: string }
Expand Down Expand Up @@ -64,8 +65,8 @@ function DecryptPostFailed({ error }: { error: Error }) {
}

interface DecryptPostProps {
postBy: string
whoAmI: string
postBy: PersonIdentifier
whoAmI: PersonIdentifier
encryptedText: string
people: Person[]
alreadySelectedPreviously: Person[]
Expand Down
2 changes: 2 additions & 0 deletions src/database/migrate/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import avatar from './old.avatar.1'
import localKeys from './old.localKeys.1'
import keys from './old.keystore.1'

avatar()
localKeys()
keys()
38 changes: 38 additions & 0 deletions src/database/migrate/old.keystore.1.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { deleteDB } from 'idb/with-async-ittr'
import * as People from '../people'
import { queryPeopleCryptoKey } from '../../key-management/keystore-db'
import { PersonIdentifier } from '../type'

/**
* ! Migrate old database into new one.
* ! Scheduled to remove it after May/31/2019
*/
export default async function migrate() {
if (indexedDB.databases) {
const dbs = await indexedDB.databases()
if (!dbs.find(x => x.name === 'maskbook-keystore-demo-v2')) return
}
// tslint:disable-next-line: deprecation
const wait = (await queryPeopleCryptoKey()).map(record => {
if (record.username === '$self')
return People.storeMyIdentityDB({
// TODO: Need to update later !
identifier: new PersonIdentifier('facebook.com', '$self'),
groups: [],
relation: [],
relationLastCheckTime: new Date(),
publicKey: record.publicKey,
privateKey: record.privateKey!,
})
else
return People.storeNewPersonDB({
identifier: new PersonIdentifier('facebook.com', record.username),
publicKey: record.publicKey,
groups: [],
relation: [],
relationLastCheckTime: new Date('May 1 2019'),
})
})
await Promise.all(wait)
await deleteDB('maskbook-keystore-demo-v2')
}
4 changes: 2 additions & 2 deletions src/database/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,13 @@ export class GroupIdentifier extends Identifier {
return new GroupIdentifier(network, groupId, virtual === 'virtual')
}
}
export class PostIdentifier extends Identifier {
export class PostIdentifier<T extends Identifier = Identifier> extends Identifier {
readonly type = 'post'
/**
* If identifier is a PostIdentifier, that means this post is binded with other post in some kind
* e.g. a comment.
*/
constructor(public identifier: Identifier, public postId: string) {
constructor(public identifier: T, public postId: string) {
super()
noSlash(postId)
}
Expand Down
17 changes: 10 additions & 7 deletions src/extension/content-script/injections/Posts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ import { usePeople } from '../../../components/DataSource/PeopleRef'
import { useAsync } from '../../../utils/components/AsyncComponent'
import { deconstructPayload } from '../../../utils/type-transform/Payload'
import Services from '../../service'
import { PersonIdentifier } from '../../../database/type'
import { PersonIdentifier, PostIdentifier } from '../../../database/type'
import { Person } from '../../../database'

const posts = new LiveSelector().querySelectorAll<HTMLDivElement>('.userContent, .userContent+*+div>div>div>div>div')

interface PostInspectorProps {
post: string
postBy: string
postBy: PersonIdentifier
postId: string
needZip(): void
}
Expand All @@ -27,11 +27,11 @@ function PostInspector(props: PostInspectorProps) {
}
if (type.encryptedPost) {
props.needZip()
const whoAmI = getUsername()!
const whoAmI = new PersonIdentifier('facebook.com', getUsername()!)
const people = usePeople()
const [alreadySelectedPreviously, setAlreadySelectedPreviously] = useState<Person[]>([])
const { iv, ownersAESKeyEncrypted } = type.encryptedPost
if (whoAmI === postBy) {
if (whoAmI.userId === postBy.userId) {
useAsync(() => Services.Crypto.getSharedListOfPost(iv), [post]).then(p => setAlreadySelectedPreviously(p))
}
return (
Expand All @@ -48,7 +48,7 @@ function PostInspector(props: PostInspectorProps) {
/>
)
} else if (type.provePost) {
Services.People.uploadProvePostUrl(postBy, postId)
Services.People.uploadProvePostUrl(new PostIdentifier(postBy, postId))
return <AddToKeyStore postBy={postBy} provePost={post} />
}
return null
Expand All @@ -57,11 +57,14 @@ new MutationObserverWatcher(posts)
.assignKeys(node => node.innerText)
.useNodeForeach((node, key, realNode) => {
// Get author
const postBy = getUsername(node.current.parentElement!.querySelectorAll('a')[1])!
const postBy = new PersonIdentifier(
'facebook.com',
getUsername(node.current.parentElement!.querySelectorAll('a')[1])!,
)
// Save author's avatar
try {
const avatar = node.current.parentElement!.querySelector('img')!
Services.People.storeAvatar(new PersonIdentifier('facebook.com', postBy), avatar.src)
Services.People.storeAvatar(postBy, avatar.src)
} catch {}
// Get post id
let postId = ''
Expand Down
3 changes: 2 additions & 1 deletion src/extension/content-script/injections/ProfilePage.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { LiveSelector } from '@holoflows/kit/es/DOM/LiveSelector'
import { MutationObserverWatcher } from '@holoflows/kit/es/DOM/Watchers/MutationObserverWatcher'
import Services from '../../service'
import { PersonIdentifier } from '../../../database/type'

const bio = new LiveSelector().querySelector<HTMLDivElement>('#profile_timeline_intro_card')
function verify(text: string) {
Expand All @@ -10,7 +11,7 @@ function verify(text: string) {
const name = a.href.match(/^https:..www.facebook.com\/(.+)/)
if (!id && !name) return
const username = id ? id[1] : name![1]
Services.Crypto.verifyOthersProve(text, username)
Services.Crypto.verifyOthersProve(text, new PersonIdentifier('facebook.com', username))
}
new MutationObserverWatcher(bio)
.useNodeForeach(node => {
Expand Down
4 changes: 3 additions & 1 deletion src/key-management/keystore-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,20 @@ class CryptoKeyRecord {
type Exporting = {
username: string
publicKey: CryptoKey
privateKey?: CryptoKey
}
/**
* @deprecated
*/
async function queryPeopleCryptoKey(): Promise<Exporting[]> {
export async function queryPeopleCryptoKey(): Promise<Exporting[]> {
async function toReadCryptoKey(y: CryptoKeyRecord): Promise<Exporting> {
const pub = await crypto.subtle.importKey('jwk', y.key.publicKey, y.algor, true, y.usages)
let priv: CryptoKey | undefined = undefined
if (y.key.privateKey) priv = await crypto.subtle.importKey('jwk', y.key.privateKey, y.algor, true, y.usages)
return {
username: y.username,
publicKey: pub,
privateKey: priv,
}
}
const query = buildQuery(new Db('maskbook-keystore-demo-v2', 1), CryptoKeyRecord)
Expand Down
5 changes: 4 additions & 1 deletion src/key-management/people-gun.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,10 @@ export async function addPersonPublicKey(user: PersonIdentifier): Promise<Person
return person
}

export async function uploadProvePostUrl(username: string, postId: string) {
export async function uploadProvePostUrl(post: PostIdentifier<PersonIdentifier>) {
const { postId, identifier } = post
if (!(identifier instanceof PersonIdentifier)) return
const { userId: username } = identifier
if (!postId) return
return gun.get('users').put({ [username]: { provePostId: postId } }).then!()
}
Expand Down
2 changes: 0 additions & 2 deletions src/network/gun/version.2.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { PostIdentifier } from '../../database/type'

export const Version2Person = '1edc22d2-ca62-4d0a-b842-148f6faa4269'
export const Version2Post = 'd7cc9636-be26-447b-a1bb-798b126f7ace'

Expand Down
5 changes: 1 addition & 4 deletions src/utils/type-transform/Username.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,8 @@ export function regularUsername(name: string) {
/**
* Normalize post url
*/
export function getPostUrlAtFacebook(post: PostIdentifier) {
export function getPostUrlAtFacebook(post: PostIdentifier<PersonIdentifier>) {
const id = post.identifier
// TODO:
if (!(id instanceof PersonIdentifier)) throw new Error('Not implemented')

const { postId } = post
const { userId } = id
if (!regularUsername(userId)) throw new TypeError(geti18nString('service_username_invalid'))
Expand Down

0 comments on commit 2bf4443

Please sign in to comment.