1 /* This file is part of Clementine.
2    Copyright 2010, David Sansome <me@davidsansome.com>
3 
4    Clementine is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8 
9    Clementine is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13 
14    You should have received a copy of the GNU General Public License
15    along with Clementine.  If not, see <http://www.gnu.org/licenses/>.
16 */
17 
18 #include "mtploader.h"
19 
20 #include <libmtp.h>
21 
22 #include "connecteddevice.h"
23 #include "mtpconnection.h"
24 #include "core/song.h"
25 #include "core/taskmanager.h"
26 #include "library/librarybackend.h"
27 
MtpLoader(const QUrl & url,TaskManager * task_manager,LibraryBackend * backend,std::shared_ptr<ConnectedDevice> device)28 MtpLoader::MtpLoader(const QUrl& url, TaskManager* task_manager,
29                      LibraryBackend* backend,
30                      std::shared_ptr<ConnectedDevice> device)
31     : QObject(nullptr),
32       device_(device),
33       url_(url),
34       task_manager_(task_manager),
35       backend_(backend) {
36   original_thread_ = thread();
37 }
38 
~MtpLoader()39 MtpLoader::~MtpLoader() {}
40 
LoadDatabase()41 void MtpLoader::LoadDatabase() {
42   int task_id = task_manager_->StartTask(tr("Loading MTP device"));
43   emit TaskStarted(task_id);
44 
45   bool success = TryLoad();
46 
47   moveToThread(original_thread_);
48 
49   task_manager_->SetTaskFinished(task_id);
50   emit LoadFinished(success);
51 }
52 
TryLoad()53 bool MtpLoader::TryLoad() {
54   MtpConnection dev(url_);
55   if (!dev.is_valid()) {
56     emit Error(tr("Error connecting MTP device"));
57     return false;
58   }
59 
60   // Load the list of songs on the device
61   SongList songs;
62   LIBMTP_track_t* tracks =
63       LIBMTP_Get_Tracklisting_With_Callback(dev.device(), nullptr, nullptr);
64   while (tracks) {
65     LIBMTP_track_t* track = tracks;
66 
67     Song song;
68     song.InitFromMTP(track, url_.host());
69     song.set_directory_id(1);
70     songs << song;
71 
72     tracks = tracks->next;
73     LIBMTP_destroy_track_t(track);
74   }
75 
76   // Need to remove all the existing songs in the database first
77   backend_->DeleteSongs(backend_->FindSongsInDirectory(1));
78 
79   // Add the songs we've just loaded
80   backend_->AddOrUpdateSongs(songs);
81 
82   return true;
83 }
84