/ packages / electron-app / src / BlogData.ts
BlogData.ts
  1  import { BlogCID } from "./BlogCID"
  2  import type { Blog, Post } from "./blog_model"
  3  import { ElectronIPFSService } from "./ElectronIPFSService"
  4  
  5  class BlogData {
  6  
  7    _blogData: Blog
  8    _ipnsName: string;
  9  
 10    ipnsName() {
 11      if (!this._ipnsName) {
 12        // old test ipns name: "k51qzi5uqu5dl8vglq0sxx6w4sh94ffz7na9ngh2vz70zzr0q7h9ouzhx8anry"
 13        this._ipnsName = "12D3KooWDyUYGDxpqxXB1fU9ykQF9DdbQJQpS8dZWtHFnqn75Lyr" 
 14      }
 15  
 16      return this._ipnsName
 17    }
 18  
 19    async loadFromIPFS() {
 20      const ipfs = new ElectronIPFSService()
 21      // TODO: Add validation that return type is blogData
 22      return ipfs.getContentIPNS(this.ipnsName())
 23    }
 24  
 25    async refreshContentFromIPFS() {
 26      console.log('refreshing from ipfs')
 27  
 28      const refreshed = this.loadFromIPFS()
 29  
 30      this.s_blogData(refreshed as any)
 31    }
 32  
 33    // FIXME: this is still using the http gateway, instead
 34    //        should publish from helia in browser node.
 35    async persistToIPFS(): Promise<string> {
 36      const data = await this.getJSON()
 37      const content = JSON.stringify(data)
 38  
 39      const ipfs = new ElectronIPFSService();
 40      const cid = await ipfs.addFileToIPFS(content)
 41  
 42      return cid
 43    }
 44  
 45    s_blogData(newBlogData: BlogData) {
 46      this._blogData = newBlogData as any;
 47    }
 48  
 49    async blogData() {
 50      if (!this._blogData) {
 51        this.refreshContentFromIPFS();
 52        // this._blogData = {
 53        //   blog_name: "Test blog",
 54        //   posts: []
 55        // }
 56      }
 57  
 58      console.log({blogData: await this._blogData})
 59  
 60      return this._blogData
 61    }
 62  
 63    async getName() {
 64      return (await this.blogData()).blog_name
 65    }
 66  
 67    async setName(newName: string) {
 68      (await this.blogData()).blog_name = newName
 69    }
 70  
 71    async getPosts() {
 72      return (await this.blogData()).posts
 73    }
 74  
 75    async getPost(id: string) {
 76      const posts = await this.getPosts()
 77      return posts.find((post) => post.id === id)
 78    }
 79  
 80    async updateIPNSName(newCID: string) {
 81      const ipfs = new ElectronIPFSService();
 82      const res = await ipfs.publishToIPNS(newCID)
 83  
 84      console.log({ipnsName: res})
 85  
 86    }
 87  
 88    async addPost(post: Post) {
 89      const current = await this.blogData();
 90      current.posts.push(post)
 91  
 92      const cid = await this.persistToIPFS()
 93      console.log("new cid: " + cid)
 94  
 95      await this.updateIPNSName(cid);
 96  
 97      const cidTracker = new BlogCID()
 98      cidTracker.setCached(cid)
 99      
100    }
101  
102    async getJSON() {
103      return this.blogData()
104    }
105  }
106  
107  export { BlogData }