File: commandqueue.cpp

package info (click to toggle)
android-file-transfer 4.5-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,496 kB
  • sloc: cpp: 12,909; python: 140; lex: 47; xml: 26; sh: 13; makefile: 6
file content (364 lines) | stat: -rw-r--r-- 10,022 bytes parent folder | download
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
354
355
356
357
358
359
360
361
362
363
364
/*
    This file is part of Android File Transfer For Linux.
    Copyright (C) 2015-2020  Vladimir Menshakov

    This library 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 2.1 of the License,
    or (at your option) any later version.

    This library 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 this library; if not, write to the Free Software Foundation,
    Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/

#include "commandqueue.h"
#include "mtpobjectsmodel.h"
#include "utils.h"

#include <QFileInfo>
#include <QDebug>
#include <QDir>
#include <QDirIterator>
#include <QApplication>

#include <mtp/metadata/Metadata.h>
#include <mtp/metadata/Library.h>
#include <mtp/scope_guard.h>

void FinishQueue::execute(CommandQueue &queue)
{ queue.finish(DirectoryId); }

void UploadFile::execute(CommandQueue &queue)
{ queue.uploadFile(Filename, Format); }

void MakeDirectory::execute(CommandQueue &queue)
{ queue.createDirectory(Filename); }

void DownloadFile::execute(CommandQueue &queue)
{ queue.downloadFile(Filename, ObjectId); }

void ImportFile::execute(CommandQueue &queue)
{ queue.importFile(Filename); }

void LoadLibrary::execute(CommandQueue &queue)
{ queue.loadLibrary(); }

void CommandQueue::loadLibrary()
{
	using namespace mtp;
	auto session = _model->session();
	qDebug() << "loading media library...";
	_library.reset();
	auto reporter = [&](Library::State state , u64 c , u64 t)
	{
		qDebug() << "progress " << static_cast<int>(state) << ", " << c << " of "<< t;
		switch(state)
		{
			case Library::State::Initialising: 		start(tr("Loading media library…")); break;
			case Library::State::QueryingArtists:	start(tr("Querying artists…")); break;
			case Library::State::LoadingArtists: 	start(tr("Loading artists…")); break;
			case Library::State::QueryingAlbums: 	start(tr("Querying albums…")); break;
			case Library::State::LoadingAlbums: 	start(tr("Loading albums…")); break;
			case Library::State::Loaded: 			start(tr("Done")); break;
		}

		if (t)
			emit total(t);

		if (c)
			emit progress(c);
	};

	try
	{ _library = std::make_shared<mtp::Library>(session, reporter); }
	catch (const std::exception & ex)
	{ qWarning() << "loading media library failed: " << ex.what(); }
}

void CommandQueue::downloadFile(const QString &filename, mtp::ObjectId objectId)
{
	if (_aborted)
		return;
	qDebug() << "downloading " << objectId << "to" << filename;

	QFileInfo fi(filename);
	QDir().mkpath(fi.dir().path());
	start(fi.fileName());
	try
	{
		model()->downloadFile(filename, objectId);
	} catch(const std::exception &ex)
	{ qDebug() << "downloading file " << filename << " failed: " << fromUtf8(ex.what()); }

	addProgress(fi.size());
}

void CommandQueue::uploadFile(const QString &filename, mtp::ObjectFormat format)
{
	if (_aborted)
		return;

	QFileInfo fi(filename);
	QString parentPath = fi.dir().path();

	qDebug() << "uploading file " << filename << ", parent: " << parentPath << ", format: " << fromUtf8(mtp::ToString(format));

	if (_directories.empty())
	{
		qDebug() << "adding first parent path";
		_directories[parentPath] = _model->parentObjectId();
		qDebug() << "directories[0]: " << parentPath << " -> " << _model->parentObjectId().Id;
	}
	start(fi.fileName());
	auto parent = _directories.find(parentPath);
	if (parent == _directories.end())
	{
		qWarning() << "invalid parent " << parentPath;
		return;
	}
	try
	{
		if (_model->parentObjectId() != parent.value()) //needed for overwrite protection
			_model->setParent(parent.value());

		_model->uploadFile(parent.value(), filename, {}, format);
	} catch(const std::exception &ex)
	{ qDebug() << "uploading file " << filename << " failed: " << fromUtf8(ex.what()); }

	addProgress(fi.size());
}

void CommandQueue::importFile(const QString &filename)
{
	if (_aborted || !_library)
		return;

	QFileInfo fi(filename);

	mtp::scope_guard r([this, &fi]() { addProgress(fi.size()); });
	std::string utfFilename = toUtf8(filename);
	mtp::ObjectFormat format = mtp::ObjectFormatFromFilename(utfFilename);

	if (mtp::IsImageFormat(format))
	{
		qDebug() << "image: " << filename;
		int score = GetCoverScore(fi.baseName());
		qDebug() << "image cover score: " << score << " for " << fi.baseName();
		auto dir = fi.dir().path();
		auto it = _covers.find(dir);
		if (it == _covers.end()) {
			Cover cover;
			cover.Score = score;
			cover.Path = filename;
			_covers.insert(std::make_pair(dir, std::move(cover)));
		} else if (score > it->second.Score) {
			it->second.Score = score;
			it->second.Path = filename;
		}

		return;
	}

	if (!mtp::IsAudioFormat(format))
		return;

	auto metadata = mtp::Metadata::Read(utfFilename);
	if (!metadata)
		return;

	qDebug() << "import: " << filename <<
		", format: " << fromUtf8(mtp::ToString(format)) <<
		", artist: " << fromUtf8(metadata->Artist) <<
		", album: " << fromUtf8(metadata->Album) <<
		", title: " << fromUtf8(metadata->Title) <<
		", year: " << metadata->Year <<
		", track: " << metadata->Track <<
		", genre: " << fromUtf8(metadata->Genre) <<
		", size: " << fi.size();


	auto artist = _library->GetArtist(metadata->Artist);
	if (!artist)
		artist = _library->CreateArtist(metadata->Artist);
	if (!artist)
	{
		qDebug() << "can't create artist";
		return;
	}

	auto album = _library->GetAlbum(artist, metadata->Album);
	if (!album)
		album = _library->CreateAlbum(artist, metadata->Album, metadata->Year);
	if (!album)
	{
		qDebug() << "can't create album";
		return;
	}

	auto dir = fi.dir().path();
	if (_albums.find(dir)== _albums.end())
	{
		qDebug() << "registering " << dir << " as a path to album";
		_albums.insert(std::make_pair(dir, album));
	}

	if (!metadata->Picture.Data.empty())
		_library->AddCover(album, metadata->Picture.Data);

	if (_library->HasTrack(album, metadata->Title, metadata->Track)) {
		qDebug() << "skipping" << filename << ", already uploaded";
		return;
	}

	auto songId = _library->CreateTrack(
		artist, album,
		format,
		metadata->Title, metadata->Genre,
		metadata->Track, toUtf8(fi.fileName()), fi.size());

	start(fi.fileName());
	_model->sendFile(filename);

	_library->AddTrack(album, songId);
}

void CommandQueue::createDirectory(const QString &srcPath)
{
	if (_aborted)
		return;

	QFileInfo fi(srcPath);
	QString parentPath = fi.dir().path();
	qDebug() << "making directory" << srcPath << ", parent: " << parentPath << ", dir: " << fi.fileName();
	if (_directories.empty())
	{
		qDebug() << "adding first parent path";
		_directories[parentPath] = _model->parentObjectId();
		qDebug() << "directories[0]: " << parentPath << " -> " << _model->parentObjectId().Id;
	}

	auto parent = _directories.find(parentPath);
	if (parent == _directories.end())
	{
		qWarning() << "invalid parent " << parentPath;
		return;
	}

	try
	{
		mtp::ObjectId dirId = _model->createDirectory(parent.value(), fi.fileName());
		_directories[srcPath] = dirId;
		qDebug() << "directories[]: " << srcPath << " -> " << dirId.Id;
	} catch(const std::exception &ex)
	{ qDebug() << "creating directory" << srcPath << "failed: " << fromUtf8(ex.what()); return; }
}

CommandQueue::CommandQueue(MtpObjectsModel *model): _model(model), _completedFilesSize(0), _aborted(false)
{
	connect(_model, SIGNAL(filePositionChanged(qint64,qint64)), this, SLOT(onFileProgress(qint64,qint64)));
	qDebug() << "upload worker started";
}

CommandQueue::~CommandQueue()
{
	qDebug() << "upload worker stopped";
}

mtp::LibraryPtr CommandQueue::library() const
{ return _library; }

void CommandQueue::execute(Command *ptr)
{
	std::unique_ptr<Command> cmd(ptr);
	try
	{ cmd->execute(*this); }
	catch(const std::exception & ex)
	{ qWarning() << "exception in command queue: " << ex.what(); }
}

void CommandQueue::start(const QString &filename)
{
	emit started(filename);
}

void CommandQueue::finish(mtp::ObjectId directoryId)
{
	qDebug() << "finishing queue";
	try
	{
		model()->setParent(directoryId);
	} catch(const std::exception &ex)
	{ qDebug() << "finalizing commands failed: " << fromUtf8(ex.what()); }

	for(auto & akv : _albums)
	{
		auto & albumPath = akv.first;
		auto & album = akv.second;

		if (_aborted)
			break;

		QString albumName = fromUtf8(akv.second->Name);
		qDebug() << "looking for a cover for album " << albumName;

		QString bestPath;
		for(auto & ckv : _covers)
		{
			auto & cover = ckv.second;

			if (cover.Path.startsWith(albumPath) && albumPath.size() > bestPath.size()) {
				bestPath = cover.Path;
			}
		}

		if (bestPath.isEmpty())
			continue;

		emit started(tr("Setting cover for album %1").arg(albumName));

		QFile file(bestPath);
		qDebug() << "setting cover from " << bestPath;
		if (!file.open(QIODevice::ReadOnly))
			continue;

		auto buffer = file.readAll();
		mtp::ByteArray value(buffer.begin(), buffer.end());
		try { _model->session()->SetObjectPropertyAsArray(album->Id, mtp::ObjectProperty::RepresentativeSampleData, value); }
		catch(const std::exception & ex)
		{ qWarning() << "setting cover failed: " << ex.what(); }
	}
	_covers.clear();

	_model->moveToThread(QApplication::instance()->thread());
	_completedFilesSize = 0;
	_directories.clear();
	_albums.clear();
	_aborted = false;
	emit finished();
}

void CommandQueue::abort()
{
	qDebug() << "aborting...";
	_aborted = true;
	_model->session()->AbortCurrentTransaction(6000);
	qDebug() << "sent abort request";
}

void CommandQueue::addProgress(qint64 fileSize)
{
	_completedFilesSize += fileSize;
	emit progress(_completedFilesSize);
}

void CommandQueue::onFileProgress(qint64 pos, qint64)
{
	//qDebug() << "on file progress " << _completedFilesSize << " " << pos;
	emit progress(_completedFilesSize + pos);
}