oauth.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. trait OAuthFunctions
  3. {
  4. public function traktOAuth()
  5. {
  6. $provider = new Bogstag\OAuth2\Client\Provider\Trakt([
  7. 'clientId' => $this->config['traktClientId'],
  8. 'clientSecret' => $this->config['traktClientSecret'],
  9. 'redirectUri' => $this->getServerPath() . 'api/v2/oauth/trakt'
  10. ]);
  11. if (!isset($_GET['code'])) {
  12. $authUrl = $provider->getAuthorizationUrl();
  13. header('Location: ' . $authUrl);
  14. exit;
  15. } elseif (empty($_GET['state'])) {
  16. exit('Invalid state');
  17. } else {
  18. try {
  19. $token = $provider->getAccessToken('authorization_code', [
  20. 'code' => $_GET['code']
  21. ]);
  22. $traktDetails = [
  23. 'traktAccessToken' => $token->getToken(),
  24. 'traktAccessTokenExpires' => gmdate('Y-m-d\TH:i:s\Z', $token->getExpires()),
  25. 'traktRefreshToken' => $token->getRefreshToken()
  26. ];
  27. $this->updateConfig($traktDetails);
  28. echo 'Details saved - Please close me!';
  29. exit;
  30. } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
  31. exit($e->getMessage());
  32. }
  33. }
  34. }
  35. public function traktOAuthRefresh()
  36. {
  37. $exp = $this->config['traktAccessTokenExpires'];
  38. $exp = date('Y-m-d\TH:i:s\Z', strtotime($exp . ' - 30 days'));
  39. if (time() - 2592000 > strtotime($exp)) {
  40. $headers = [
  41. 'Content-Type' => 'application/json'
  42. ];
  43. $data = [
  44. 'refresh_token' => $this->config['traktRefreshToken'],
  45. 'clientId' => $this->config['traktClientId'],
  46. 'clientSecret' => $this->config['traktClientSecret'],
  47. 'redirectUri' => $this->getServerPath() . 'api/v2/oauth/trakt',
  48. 'grant_type' => 'refresh_token'
  49. ];
  50. $url = $this->qualifyURL('https://api.trakt.tv/oauth/token');
  51. try {
  52. $response = Requests::post($url, $headers, json_encode($data), []);
  53. if ($response->success) {
  54. $data = json_decode($response->body, true);
  55. $newExp = date('Y-m-d\TH:i:s\Z', strtotime($this->currentTime . ' + 90 days'));
  56. $traktDetails = [
  57. 'traktAccessToken' => $data['access_token'],
  58. 'traktAccessTokenExpires' => $newExp,
  59. 'traktRefreshToken' => $data['refresh_token']
  60. ];
  61. $this->updateConfig($traktDetails);
  62. return true;
  63. }
  64. } catch (Requests_Exception $e) {
  65. $this->writeLog('error', 'Trakt Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  66. $this->setAPIResponse('error', $e->getMessage(), 500);
  67. return false;
  68. }
  69. }
  70. }
  71. }