|
@@ -0,0 +1,75 @@
|
|
|
+import { Injectable } from "@angular/core";
|
|
|
+import { TwitterApiProvider } from "../twitter-api/twitter-api";
|
|
|
+import { P2pStorageIpfsProvider } from "../p2p-storage-ipfs/p2p-storage-ipfs";
|
|
|
+import { Storage } from "@ionic/storage";
|
|
|
+
|
|
|
+@Injectable()
|
|
|
+export class CryptoProvider {
|
|
|
+ ownUserId: string;
|
|
|
+
|
|
|
+ constructor(
|
|
|
+ private twitter: TwitterApiProvider,
|
|
|
+ private ipfs: P2pStorageIpfsProvider,
|
|
|
+ private storage: Storage
|
|
|
+ ) {
|
|
|
+ this.init();
|
|
|
+ }
|
|
|
+
|
|
|
+ private async init() {
|
|
|
+ this.ownUserId = await this.storage.get("userId");
|
|
|
+ }
|
|
|
+
|
|
|
+ public async publishPublicKey(key: string) {
|
|
|
+ let publicKeyHistory;
|
|
|
+
|
|
|
+ // Get user description
|
|
|
+ const userData = await this.twitter.fetchUser(this.ownUserId);
|
|
|
+ const profileDescription = userData["description"];
|
|
|
+
|
|
|
+ // Extract link to public key
|
|
|
+ const link = this.extractLinkFromDescription(profileDescription);
|
|
|
+
|
|
|
+ // Fetch public key history
|
|
|
+ if (link.length) {
|
|
|
+ publicKeyHistory = await this.ipfs.fetchJson(link);
|
|
|
+ }
|
|
|
+
|
|
|
+ // Todo: avoid publishing the same public key twice - check if new key equals newest key in history
|
|
|
+
|
|
|
+ // Add new key to history
|
|
|
+ const newKey = {
|
|
|
+ key: key,
|
|
|
+ validFrom: Date.now()
|
|
|
+ };
|
|
|
+
|
|
|
+ if (link.length) {
|
|
|
+ publicKeyHistory["keys"].push(newKey);
|
|
|
+ } else {
|
|
|
+ publicKeyHistory = {
|
|
|
+ keys: [newKey]
|
|
|
+ };
|
|
|
+ }
|
|
|
+
|
|
|
+ // Publish updated key history...
|
|
|
+ const res = await this.ipfs.storePublicKey(publicKeyHistory);
|
|
|
+
|
|
|
+ // ... and update description in user profile
|
|
|
+ this.twitter.updateProfileDescription(
|
|
|
+ "ipfs://" + res["Hash"] + " #hybridOSN"
|
|
|
+ );
|
|
|
+ }
|
|
|
+
|
|
|
+ private extractLinkFromDescription(profileDescription: string): string {
|
|
|
+ for (let word of profileDescription.split(" ")) {
|
|
|
+ if (this.isLink(word)) {
|
|
|
+ return word.substr(7);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return "";
|
|
|
+ }
|
|
|
+
|
|
|
+ private isLink(word: string): boolean {
|
|
|
+ const hits = word.match(/ipfs:\/\/Qm[a-zA-Z0-9]+/);
|
|
|
+ return hits != null;
|
|
|
+ }
|
|
|
+}
|