You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
2.2 KiB

  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2019 Joas Schilling <coding@schilljs.com>
  5. *
  6. * @license GNU AGPL version 3 or any later version
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU Affero General Public License as
  10. * published by the Free Software Foundation, either version 3 of the
  11. * License, or (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU Affero General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. if (PHP_SAPI !== 'cli') {
  23. // Only allow access via the console
  24. exit;
  25. }
  26. if ($argc < 2) {
  27. echo 'Missing search term in call to hackernews.php';
  28. return 1;
  29. }
  30. $mode = $argv[1];
  31. if ($mode === '--help' || !in_array($mode, ['top', 'new', 'best', ''], true)) {
  32. echo '/hackernews - A simple command to list the Top 5 top, new or best stories' . "\n";
  33. echo "\n";
  34. echo 'Example: /hackernews top' . "\n";
  35. return;
  36. }
  37. $mode = $mode ?: 'top';
  38. $endpoint = 'https://hacker-news.firebaseio.com/v0/' . $mode . 'stories.json';
  39. $content = file_get_contents($endpoint);
  40. $results = json_decode($content, true);
  41. $stories = array_slice($results, 0, 5);
  42. $response = 'Hackernews ' . ucfirst($mode) . ' 5:' . "\n";
  43. $length = 120;
  44. foreach ($stories as $storyId) {
  45. $endpoint = 'https://hacker-news.firebaseio.com/v0/item/' . $storyId . '.json';
  46. $content = file_get_contents($endpoint);
  47. $result = json_decode($content, true);
  48. $link = " - {$result['url']}\n";
  49. $remainingLength = max(strlen($result['title']), $length - strlen($link));
  50. if ($remainingLength < strlen('* ' . $result['title'])) {
  51. $response .= substr('* ' . $result['title'], 0, $remainingLength) . '…' . $link;
  52. } else {
  53. $response .= '* ' . $result['title'] . $link;
  54. }
  55. }
  56. $page = 'news';
  57. if ($mode === 'new') {
  58. $page = 'newest';
  59. } elseif ($mode === 'best') {
  60. $page = 'best';
  61. }
  62. $response .= "Find more at https://news.ycombinator.com/$page";
  63. echo($response);