mastodon.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace HalcyonSuite\HalcyonForMastodon;
  3. require_once('mastodon-api/mastodon.php');
  4. use Exception;
  5. class Mastodon extends \Mastodon_api {
  6. function __construct(){
  7. $appSettings = parse_ini_file('../config.ini',true);
  8. $this->datadir = "../data";
  9. $this->clientName = $appSettings["App"]["api_client_name"];
  10. $this->clientRedirectUris = $appSettings["App"]["api_client_website"].'/auth urn:ietf:wg:oauth:2.0:oob';
  11. $this->clientWebsite = $appSettings["App"]["api_client_website"];
  12. $this->clientScopes = array('read','write','follow');
  13. $this->instances = array();
  14. $this->readInstances();
  15. }
  16. private function newInstance($domain) {
  17. $res = $this->create_app($this->clientName,$this->clientScopes,$this->clientRedirectUris,$this->clientWebsite);
  18. if(isset($res['html']['client_id'])) {
  19. $this->instances[$domain] = $res['html'];
  20. file_put_contents($this->datadir."/".substr($domain,8).".txt",json_encode(array("client_id" => $res['html']['client_id'],"client_secret" => $res['html']['client_secret'])));
  21. }
  22. else {
  23. throw new Exception("Invalid instance");
  24. }
  25. }
  26. public function selectInstance($domain) {
  27. $this->set_url($domain);
  28. if(!$this->instanceExists($domain)) {
  29. $this->newInstance($domain);
  30. }
  31. $this->set_client($this->instances[$domain]['client_id'],$this->instances[$domain]['client_secret']);
  32. }
  33. public function getInstance($domain) {
  34. $this->set_url($domain);
  35. if (!$this->instanceExists($domain)) {
  36. $this->newInstance($domain);
  37. }
  38. return array('client_id' => $this->instances[$domain]['client_id'],'client_secret' => $this->instances[$domain]['client_secret']);
  39. }
  40. public function instanceExists($domain) {
  41. return isset($this->instances[$domain]);
  42. }
  43. private function readInstances() {
  44. $instlist = array_diff(scandir($this->datadir),array("..",".",".htaccess"));
  45. foreach($instlist as $index => $item) {
  46. $itemname = "https://".substr($item,0,-4);
  47. $this->instances[$itemname] = json_decode(file_get_contents($this->datadir."/".$item),true);
  48. }
  49. }
  50. }
  51. ?>