<?php
require_once __DIR__ . '/config.php';

// First, login
$cLogin = curl_init($base . 'api/greader.php/accounts/ClientLogin?Email=' . $user . '&Passwd=' . $pass);
curl_setopt($cLogin, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($cLogin, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($cLogin, CURLOPT_RETURNTRANSFER, true);
$keys = curl_exec($cLogin);
curl_close($cLogin);

// Then we fetch our feed (max 1000 elements) excluding those marked as read
$ch = curl_init($base . 'api/greader.php/reader/api/0/stream/contents/reading-list?n=1000&xt=user/-/state/com.google/read');
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'Authorization:GoogleLogin ' . str_replace('Auth=','auth=', explode("\n", $keys)[2])
));
$out = curl_exec($ch);
$json = json_decode($out);
curl_close($ch);

// We'll now go thru the results
$out = [];
foreach ($json->items as $item) {
  // If the source matches the exclude list, ignore
  if (in_array($item->origin->title, $exclude)) continue;
  // If it has a Newsletters label, ignore
  if (in_array('user/-/label/Newsletters', $item->categories)) continue;

  $u = $item->alternate[0]->href;
  $out[] = array(
    'id' => $item->id,
    'title' => $item->title,
    'source' => $item->origin->title,
    'link' => empty($u) ? $base . 'i/' : $u
  );
}

// And we save the results as json
file_put_contents('public/rss.json', json_encode($out));