about summary refs log tree commit diff stats
path: root/src/timeline.cpp
blob: fd75a69013cdbe774ffadba9143de7d6914012db (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include "timeline.h"
#include <sstream>
#include <json.hpp>
#include "codes.h"
#include "util.h"
#include "request.h"

namespace twitter {

  timeline::timeline(
    const auth& tauth,
    std::string url) :
      auth_(tauth),
      url_(std::move(url))
  {
  }

  std::list<tweet> timeline::poll()
  {
    tweet_id maxId;
    std::list<tweet> result;

    for (int i = 0; i < 5; i++)
    {
      std::ostringstream urlstr;
      urlstr << url_;

      std::list<std::string> arguments;

      if (i > 0)
      {
        arguments.push_back("max_id=" + std::to_string(maxId));
      }

      if (hasSince_)
      {
        arguments.push_back("since_id=" + std::to_string(sinceId_));
      }

      if (!arguments.empty())
      {
        urlstr << "?";
        urlstr << implode(std::begin(arguments), std::end(arguments), "&");
      }

      std::string theUrl = urlstr.str();
      std::string response = get(auth_, theUrl).perform();

      try
      {
        nlohmann::json rjs = nlohmann::json::parse(response);

        if (rjs.empty())
        {
          break;
        }

        for (auto& single : rjs)
        {
          result.emplace_back(single.dump());
        }
      } catch (const std::invalid_argument& error)
      {
        std::throw_with_nested(invalid_response(response));
      } catch (const std::domain_error& error)
      {
        std::throw_with_nested(invalid_response(response));
      }

      maxId = result.back().getID() - 1;
    }

    if (!result.empty())
    {
      sinceId_ = result.front().getID();
      hasSince_ = true;
    }

    return result;
  }

};