File: series_puller.cpp

package info (click to toggle)
sight 25.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 42,184 kB
  • sloc: cpp: 289,476; xml: 17,257; ansic: 9,878; python: 1,379; sh: 144; makefile: 33
file content (353 lines) | stat: -rw-r--r-- 13,132 bytes parent folder | download | duplicates (2)
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/************************************************************************
 *
 * Copyright (C) 2018-2025 IRCAD France
 * Copyright (C) 2018-2019 IHU Strasbourg
 *
 * This file is part of Sight.
 *
 * Sight is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Sight is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Sight. If not, see <https://www.gnu.org/licenses/>.
 *
 ***********************************************************************/

#include "series_puller.hpp"

#include "detail/query.hpp"

#include <core/com/signal.hxx>
#include <core/com/slots.hxx>
#include <core/progress/observer.hpp>
#include <core/tools/system.hpp>

#include <data/image_series.hpp>

#include <io/dicom/helper/series.hpp>
#include <io/dicom/reader/file.hpp>
#include <io/http/exceptions/base.hpp>
#include <io/http/helper/series.hpp>
#include <io/http/request.hpp>

#include <service/extension/config.hpp>
#include <service/op.hpp>

#include <ui/__/dialog/message.hpp>
#include <ui/__/dialog/progress.hpp>
#include <ui/__/preferences.hpp>

#include <qdebug.h>

#include <algorithm>
#include <filesystem>

namespace sight::module::io::dicomweb
{

//------------------------------------------------------------------------------

series_puller::series_puller() noexcept :
    has_monitors(m_signals)
{
}

//------------------------------------------------------------------------------

void series_puller::configuring()
{
}

//------------------------------------------------------------------------------

void series_puller::starting()
{
    // Create temporary series_set
    m_tmp_series_set = std::make_shared<data::series_set>();
}

//------------------------------------------------------------------------------

void series_puller::stopping()
{
    {
        const auto series_set     = m_series_set.lock();
        const auto scoped_emitter = series_set->scoped_emit();

        // Delete old series from the series_set.
        series_set->clear();
    }
}

//------------------------------------------------------------------------------

void series_puller::updating()
{
    if(m_is_pulling)
    {
        // Display a message to inform the user that the service is already pulling data.
        sight::ui::dialog::message message_box;
        message_box.set_title("Pulling Series");
        message_box.set_message(
            "The service is already pulling data. Please wait until the pulling is done "
            "before sending a new pull request."
        );
        message_box.set_icon(ui::dialog::message::info);
        message_box.add_button(ui::dialog::message::ok);
        message_box.show();
    }
    else
    {
        const auto selected_series = m_selected_series.lock();
        if(selected_series->empty())
        {
            // Display a message to inform the user that there is no series selected.
            sight::ui::dialog::message message_box;
            message_box.set_title("Pulling Series");
            message_box.set_message("Unable to pull series, there is no series selected. ");
            message_box.set_icon(ui::dialog::message::info);
            message_box.add_button(ui::dialog::message::ok);
            message_box.show();
        }
        else
        {
            this->pull_series();
        }
    }
}

//------------------------------------------------------------------------------

void series_puller::pull_series()
{
    // Catch any errors
    try
    {
        // Clear map of Dicom series being pulled
        m_pulling_dicom_series_map.clear();

        // Set pulling boolean to true
        m_is_pulling = true;

        // Reset Counters
        m_series_index = 0;
        std::size_t instance_count = 0;

        const auto selected_series = m_selected_series.lock();

        // Find which selected series must be pulled
        dicom_series_container_t pull_series_vector;
        dicom_series_container_t selected_series_vector;

        auto it = selected_series->cbegin();
        for( ; it != selected_series->cend() ; ++it)
        {
            data::series::sptr series = std::dynamic_pointer_cast<data::series>(*it);

            // Check if the series must be pulled
            if(series
               && std::ranges::find(
                   m_local_series,
                   series->get_series_instance_uid()
               ) == m_local_series.end())
            {
                // Add series in the pulling series map
                m_pulling_dicom_series_map[series->get_series_instance_uid()] = series;

                pull_series_vector.push_back(series);
                instance_count += static_cast<std::size_t>(series->get_instance_number().value());
            }

            selected_series_vector.push_back(series);
        }

        // Pull series
        if(!pull_series_vector.empty())
        {
            auto progress = std::make_shared<core::progress::observer>("Pull series", instance_count);
            this->async_emit(core::progress::has_monitors::signals::MONITOR_CREATED, progress->get_sptr());

            std::size_t done = 0;
            /// GET
            const auto& series_instances_ui_ds =
                sight::io::http::helper::series::to_series_instance_uid_container(pull_series_vector);
            for(const std::string& series_instances_uid : series_instances_ui_ds)
            {
                // Find Series according to SeriesInstanceUID
                QJsonObject query;
                query.insert("SeriesInstanceUID", series_instances_uid.c_str());

                QJsonObject body;
                body.insert("Level", "Series");
                body.insert("Query", query);
                body.insert("Limit", 0);

                /// Url PACS
                const std::string pacs_server("http://" + *m_server_hostname + ":" + std::to_string(*m_server_port));

                /// Orthanc "/tools/find" route. POST a JSON to get all Series corresponding to the SeriesInstanceUID.
                sight::io::http::request::sptr request = sight::io::http::request::New(
                    pacs_server + "/tools/find"
                );
                QByteArray series_answer;
                try
                {
                    series_answer = m_client_qt.post(request, QJsonDocument(body).toJson());
                }
                catch(sight::io::http::exceptions::host_not_found& exception)
                {
                    std::stringstream ss;
                    ss << "Host not found:\n"
                    << " Please check your configuration: \n"
                    << "Pacs host name: " << *m_server_hostname << "\n"
                    << "Pacs port: " << *m_server_port << "\n";

                    sight::module::io::dicomweb::series_puller::display_error_message(ss.str());
                    SIGHT_WARN(exception.what());
                }

                QJsonDocument json_response    = QJsonDocument::fromJson(series_answer);
                const QJsonArray& series_array = json_response.array();

                const auto series_array_size = series_array.count();
                for(auto i = 0 ; i < series_array_size ; ++i)
                {
                    const std::string& series_uid = series_array.at(i).toString().toStdString();

                    /// GET all Instances by Series.
                    const std::string& instances_url(std::string(pacs_server) + "/series/" + series_uid);
                    const QByteArray& instances_answer =
                        m_client_qt.get(sight::io::http::request::New(instances_url));
                    json_response = QJsonDocument::fromJson(instances_answer);
                    const QJsonObject& json_obj       = json_response.object();
                    const QJsonArray& instances_array = json_obj["Instances"].toArray();

                    qDebug() << json_obj;
                    const auto instances_array_size = instances_array.count();
                    for(auto j = 0 ; j < instances_array_size ; ++j)
                    {
                        // This the instance ID on the server, which may be different from the InstanceUID
                        const std::string& instance_server_id = instances_array.at(j).toString().toStdString();

                        // Retrieve the SOP Instance UID
                        const auto instance_uid = detail::query_instance_uid(
                            pacs_server,
                            instance_server_id,
                            m_client_qt
                        );
                        /// GET DICOM Instance file.
                        const std::string instance_url(pacs_server + "/instances/" + instance_server_id + "/file");

                        const auto path = sight::io::dicom::helper::series::get_path(
                            series_instances_uid,
                            instance_uid
                        );
                        try
                        {
                            m_client_qt.get_file(sight::io::http::request::New(instance_url), path);
                        }
                        catch(sight::io::http::exceptions::content_not_found& exception)
                        {
                            std::stringstream ss;
                            ss << "Content not found:  \n"
                            << "Unable to download the DICOM instance. \n";

                            sight::module::io::dicomweb::series_puller::display_error_message(ss.str());
                            SIGHT_WARN(exception.what());
                        }
                        progress->done_work(++done);
                    }
                }
            }
        }

        // Read series if there is no error
        if(m_is_pulling)
        {
            this->read_local_series(selected_series_vector);
        }

        // Set pulling boolean to false
        m_is_pulling = false;
    }
    catch(sight::io::http::exceptions::base& exception)
    {
        std::stringstream ss;
        ss << "Unknown error.";
        sight::module::io::dicomweb::series_puller::display_error_message(ss.str());
        SIGHT_WARN(exception.what());
        m_is_pulling = false;
    }
}

//------------------------------------------------------------------------------

void series_puller::read_local_series(dicom_series_container_t _selected_series)
{
    const auto dest_series_set = m_series_set.lock();

    const auto scoped_emitter = dest_series_set->scoped_emit();

    // Read only series that are not in the series_set
    const instance_uid_container_t& already_loaded_series =
        sight::io::http::helper::series::to_series_instance_uid_container(dest_series_set->get_content());

    for(const auto& series : _selected_series)
    {
        SIGHT_ASSERT("DicomSeries should not be null !", series);
        const std::string& selected_series_uid = series->get_series_instance_uid();

        // Add the series to the local series vector
        if(std::ranges::find(m_local_series, selected_series_uid) == m_local_series.end())
        {
            m_local_series.push_back(selected_series_uid);
        }

        // Check if the series is loaded
        if(std::ranges::find(
               already_loaded_series,
               selected_series_uid
           ) == already_loaded_series.cend())
        {
            // Clear temporary series
            m_tmp_series_set->clear();

            auto path   = sight::io::dicom::helper::series::get_path(*series);
            auto reader = std::make_shared<sight::io::dicom::reader::file>();

            reader->set_object(dest_series_set.get_shared());
            reader->set_folder({path.string()});

            auto observer = std::make_shared<sight::core::progress::observer>("Read image series");
            this->async_emit(core::progress::has_monitors::signals::MONITOR_CREATED, observer->get_sptr());
            reader->read(observer);

            // Merge series
            std::copy(m_tmp_series_set->cbegin(), m_tmp_series_set->cend(), sight::data::inserter(*dest_series_set));
        }
    }
}

//------------------------------------------------------------------------------

void series_puller::display_error_message(const std::string& _message)
{
    SIGHT_WARN("Error: " + _message);
    sight::ui::dialog::message message_box;
    message_box.set_title("Error");
    message_box.set_message(_message);
    message_box.set_icon(ui::dialog::message::critical);
    message_box.add_button(ui::dialog::message::ok);
    message_box.show();
}

//------------------------------------------------------------------------------

} // namespace sight::module::io::dicomweb