OSDN Git Service

Correct that the head of downloaded contents is not captured.
[fukui-no-namari/dialektos.git] / src / board_window.cxx
1 /*
2  * Copyright (C) 2009 by Aiwota Programmer
3  * aiwotaprog@tetteke.tk
4  *
5  * This file is part of Dialektos.
6  *
7  * Dialektos is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * Dialektos is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with Dialektos.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include "board_window.hxx"
22
23 #include <glibmm/ustring.h>
24 #include <glibmm/refptr.h>
25 #include <sigc++/functors/mem_fun.h>
26 #include <sigc++/signal.h>
27
28 #include <boost/date_time/posix_time/posix_time.hpp>
29 #include <boost/lexical_cast.hpp>
30 #include <boost/filesystem.hpp>
31 #include <boost/format.hpp>
32 #include <boost/bind.hpp>
33 #include <boost/foreach.hpp>
34 #include <boost/mpl/find.hpp>
35
36 #include <string>
37 #include <fstream>
38 #include <iostream>
39 #include <sstream>
40
41 #include "bbs_detail_base.hxx"
42 #include "thread_list_model.hxx"
43 #include "board_view_column.hxx"
44 #include "board_subject_item.hxx"
45 #include "thread_idx_cache.hxx"
46 #include "uri_opener.hxx"
47 #include "http_get.hxx"
48 #include "board_subject_idx.hxx"
49 #include "http_date.hxx"
50 #include "misc.hxx"
51
52
53 namespace dialektos {
54
55
56 void BoardWindow::create(std::auto_ptr<bbs_detail::Base> bbs) {
57   regist(new BoardWindow(bbs));
58 }
59
60 BoardWindow::BoardWindow(std::auto_ptr<bbs_detail::Base> bbs) :
61   ApplicationFrameWork(), tree_view_(), bbs_(bbs), scrolled_(),
62   tree_model_(ThreadListModel::create()),
63   http_getter_()
64   {
65
66   // additional menuitems for board window
67   action_group_->add(Gtk::Action::create("FileOpen", "_Open Thread"),
68       sigc::mem_fun(*this, &BoardWindow::on_action_file_open));
69
70   Glib::ustring ui =
71     "<ui>"
72     "  <menubar name='MenuBar'>"
73     "    <menu action='MenuFile'>"
74     "      <menuitem action='FileOpen'/>"
75     "    </menu>"
76     "  </menubar>"
77     "  <popup name='MenuPopup'>"
78     "    <menuitem action='FileOpen'/>"
79     "  </popup>"
80     "</ui>";
81
82   ui_manager_->add_ui_from_string(ui);
83
84
85   tree_view_.signal_row_activated().connect(
86       sigc::mem_fun(*this, &BoardWindow::on_row_activated));
87   tree_view_.signal_button_press_event().connect_notify(
88       sigc::mem_fun(*this, &BoardWindow::on_child_button_press));
89
90   set_default_size(400,300);
91
92   scrolled_.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
93   add(scrolled_);
94   scrolled_.add(tree_view_);
95
96   tree_view_.set_model(tree_model_);
97   tree_view_.set_fixed_height_mode(true);
98   tree_view_.set_rules_hint(true);
99
100   tree_view_.append_column(*Gtk::manage(new view_column::Number));
101   tree_view_.append_column(*Gtk::manage(new view_column::Title));
102   tree_view_.append_column(*Gtk::manage(new view_column::ResNum));
103   tree_view_.append_column(*Gtk::manage(new view_column::LineCount));
104   tree_view_.append_column(*Gtk::manage(new view_column::Average));
105   tree_view_.append_column(*Gtk::manage(new view_column::StartTime));
106
107   using namespace boost::posix_time;
108   ptime start = microsec_clock::local_time();
109
110   load();
111
112   std::cout <<
113   to_simple_string(microsec_clock::local_time() - start) << std::endl;
114
115   show_all();
116 }
117
118 BoardWindow::~BoardWindow() {
119 }
120
121 void BoardWindow::on_row_activated(const Gtk::TreeModel::Path& path,
122     Gtk::TreeViewColumn* /*col*/) {
123   Gtk::TreeIter iter = tree_model_->get_iter(path);
124   std::string id;
125   iter->get_value(boost::mpl::find<model_column::List,
126       model_column::ID>::type::pos::value, id);
127
128   const std::string uri = bbs_->get_another_thread_uri(id);
129   uri_opener::open(uri);
130 }
131
132 void BoardWindow::on_action_view_stop() {
133   if (http_getter_) http_getter_->cancel();
134 }
135
136 bool BoardWindow::is_same(const bbs_detail::Base& bbs) const {
137   return *bbs_ == bbs;
138 }
139
140 std::string BoardWindow::get_uri() const {
141   return bbs_->get_board_uri();
142 }
143
144
145 void BoardWindow::load() {
146   boost::unordered_map<model_column::ID::type, ModelColumns> buffer;
147
148   std::vector<ThreadIdxCache> caches;
149
150   const boost::filesystem::path dir(bbs_->get_board_idx_dir_path());
151   if (boost::filesystem::exists(dir) && boost::filesystem::is_directory(dir))
152     caches = dialektos::ThreadIdxCache::from_directory(dir);
153
154   BOOST_FOREACH(const ThreadIdxCache& cache, caches) {
155     ModelColumns cols;
156     model_column::field<model_column::Title>(cols) = cache.title_;
157     model_column::field<model_column::ID>(cols) = cache.id_;
158     model_column::field<model_column::LineCount>(cols) = cache.line_count_;
159     buffer[cache.id_] = cols;
160   }
161
162   const boost::filesystem::path sbj(bbs_->get_board_subject_path());
163   if (boost::filesystem::exists(sbj) && boost::filesystem::is_regular(sbj)) {
164     std::vector<SubjectItem> subjects;
165     bbs_->load_subject(subjects);
166
167     idx_ = SubjectIdx::from_xml(
168         boost::filesystem::path(bbs_->get_board_subject_idx_path()));
169
170     merge_subject_txt(subjects, buffer);
171   }
172
173   tree_model_->set_buffer(buffer);
174 }
175
176 void BoardWindow::merge_subject_txt(
177     const std::vector<SubjectItem>& subjects,
178     boost::unordered_map<std::string, ModelColumns>& buffer) {
179
180   boost::posix_time::ptime last_modified;
181   try {
182     last_modified = rfc1123_to_ptime(idx_.last_modified_);
183   } catch (const HTTPDateError& e) {
184     std::cerr << e.what() << std::endl;
185     last_modified = boost::posix_time::second_clock::universal_time();
186   }
187
188   BOOST_FOREACH(const SubjectItem& item, subjects) {
189     ModelColumns& cols = buffer[item.id_];
190     model_column::field<model_column::Number>(cols) = item.number_;
191     model_column::field<model_column::Title>(cols) = item.title_;
192     model_column::field<model_column::ID>(cols) = item.id_;
193     model_column::field<model_column::ResNum>(cols) = item.res_num_;
194
195     try {
196       const std::time_t _start = boost::lexical_cast<std::time_t>(item.id_);
197       const boost::posix_time::ptime start = boost::posix_time::from_time_t(_start);
198       const boost::posix_time::ptime curr = last_modified;
199       const boost::posix_time::time_duration dur = curr - start;
200       const double sec = dur.total_seconds();
201       const double average = item.res_num_ / (sec/60.0/60.0/24.0);
202       model_column::field<model_column::Average>(cols) = average;
203     } catch(const boost::bad_lexical_cast& e) {
204       std::cerr << e.what() << "(" << item.id_ << ")" << std::endl;
205     }
206   }
207 }
208
209 void BoardWindow::unmerge_subject_txt(
210     boost::unordered_map<std::string, ModelColumns>& buffer) {
211   // remove thread ids which line_count_ is zero.
212   std::list<std::string> remove_list;
213   typedef boost::unordered_map<std::string, ModelColumns>::value_type PairType;
214   BOOST_FOREACH(PairType& pair, buffer) {
215     ModelColumns& cols = pair.second;
216     if (model_column::field<model_column::LineCount>(cols) == 0)
217       remove_list.push_back(pair.first);
218     else if (model_column::field<model_column::Number>(cols) != 0) {
219       model_column::field<model_column::Number>(cols) = 0;
220       model_column::field<model_column::ResNum>(cols) = 0;
221       model_column::field<model_column::Average>(cols) = 0;
222     }
223   }
224   BOOST_FOREACH(const std::string& id, remove_list)
225     buffer.erase(id);
226 }
227
228 void BoardWindow::on_action_file_open() {
229   std::cout << "file open activated" << std::endl;
230 }
231
232 void BoardWindow::on_action_view_refresh() {
233   if (http_getter_) return;
234
235   statusbar_.push("HTTP/1.0 GET...");
236
237   const std::string uri = bbs_->get_board_subject_uri();
238   http::Header request_header = bbs_->get_board_subject_request_header();
239
240   SubjectIdx idx = SubjectIdx::from_xml(
241       boost::filesystem::path(bbs_->get_board_subject_idx_path()));
242   request_header.set_if_modified_since(idx.last_modified_);
243
244   http_getter_.reset(new http::GetInThread(uri, request_header));
245   http_getter_->signal_end().connect(
246       sigc::mem_fun(*this, &BoardWindow::on_http_get_end));
247   http_getter_->run();
248 }
249
250 void BoardWindow::save_content(const http::Response& response) {
251   // save the content to the file subject.txt
252   if (!misc::create_directories(boost::filesystem::path(
253           bbs_->get_board_subject_path()).parent_path())) return;
254   std::ofstream ofs(bbs_->get_board_subject_path().c_str());
255   ofs << response.get_content();
256   ofs.close();
257
258   // save the metadata to the file subject.xml
259   idx_.last_modified_ = response.get_header().get_last_modified();
260   idx_.to_xml(boost::filesystem::path(bbs_->get_board_subject_idx_path()));
261 }
262
263 void BoardWindow::on_http_get_end(bool success) {
264 //  const std::string uri = http_getter_->get_uri();
265 //  const http::Header request_header = http_getter_->get_request_header();
266   const http::Response response = http_getter_->get_response();
267   const boost::system::error_code err = http_getter_->get_error();
268   http_getter_.reset(0);
269   if (err) {
270     statusbar_.push(err.message());
271     return;
272   }
273   if (!success) {
274     statusbar_.push("Canceled.");
275     return;
276   }
277
278   on_refresh_end(response.get_status_line(), response.get_header());
279
280   std::vector<SubjectItem> subjects;
281   bbs_->load_subject_from_string(response.get_content(), subjects);
282
283   if (subjects.empty()) return;
284
285   save_content(response);
286
287   boost::unordered_map<std::string, ModelColumns> buffer;
288   tree_model_->get_buffer(buffer);
289   unmerge_subject_txt(buffer);
290   merge_subject_txt(subjects, buffer);
291   tree_model_->set_buffer(buffer);
292 }
293
294 void BoardWindow::on_refresh_end(const http::StatusLine& status,
295     const http::Header& header) {
296   std::string message = status.get_line();
297   const std::string last_modified = header.get_last_modified();
298   if (!last_modified.empty()) {
299     message += " ";
300     message += last_modified;
301   }
302   statusbar_.push(message);
303 }
304
305 } // namespace dialektos