write-tweet.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { Component } from "@angular/core";
  2. import {
  3. IonicPage,
  4. NavController,
  5. NavParams,
  6. LoadingController
  7. } from "ionic-angular";
  8. import { FormBuilder, Validators, FormGroup } from "@angular/forms";
  9. import { TwitterApiProvider } from "../../providers/twitter-api/twitter-api";
  10. import { HttpClient } from "@angular/common/http";
  11. import { Storage } from "@ionic/storage";
  12. import Gun from "gun";
  13. /**
  14. * Generated class for the WriteTweetPage page.
  15. *
  16. * See https://ionicframework.com/docs/components/#navigation for more info on
  17. * Ionic pages and navigation.
  18. */
  19. @IonicPage()
  20. @Component({
  21. selector: "page-write-tweet",
  22. templateUrl: "write-tweet.html"
  23. })
  24. export class WriteTweetPage {
  25. tweet: FormGroup;
  26. gun;
  27. constructor(
  28. public navCtrl: NavController,
  29. public navParams: NavParams,
  30. private formBuilder: FormBuilder,
  31. private twitter: TwitterApiProvider,
  32. private loadingCtrl: LoadingController,
  33. private http: HttpClient,
  34. private storage: Storage
  35. ) {
  36. this.gun = Gun();
  37. this.tweet = this.formBuilder.group({
  38. text: ["", Validators.maxLength(140)],
  39. p2p: [false]
  40. });
  41. }
  42. ionViewDidLoad() {}
  43. get tweetCharProgress() {
  44. let progress = 1 - this.tweet.value["text"].length / 140;
  45. let radius = 8;
  46. let circumference = Math.PI * radius * 2;
  47. return progress * circumference;
  48. }
  49. async submitTweet() {
  50. let loading = this.loadingCtrl.create();
  51. loading.present();
  52. if (this.tweet.value.p2p) {
  53. let hash = await this.postToIpfs(this.tweet.value["text"]);
  54. this.gun.get("username").put({ lastTweet: hash });
  55. } else {
  56. await this.twitter.tweet(this.tweet.value["text"]);
  57. }
  58. loading.dismiss();
  59. this.navCtrl.pop();
  60. }
  61. private async postToIpfs(text) {
  62. let url = "https://ipfs.infura.io:5001/api/v0/add";
  63. let data = {
  64. text: this.tweet.value["text"].trim(),
  65. userId: await this.storage.get("userId"),
  66. timestamp: Date.now()
  67. };
  68. let formData = new FormData();
  69. formData.append("data", JSON.stringify(data));
  70. let res = await this.http.post(url, formData).toPromise();
  71. console.log(res["Hash"]);
  72. return res["Hash"];
  73. }
  74. }