1/* 2 * This file Copyright (C) Mnemosyne LLC 3 * 4 * This program is free software; you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License version 2 6 * as published by the Free Software Foundation. 7 * 8 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html 9 * 10 * $Id: add-data.cc 12697 2011-08-20 05:19:27Z jordan $ 11 */ 12 13#include <QFile> 14 15#include <libtransmission/transmission.h> 16#include <libtransmission/bencode.h> // tr_base64_encode() 17#include <libtransmission/utils.h> // tr_base64_encode() 18 19#include "add-data.h" 20#include "utils.h" 21 22int 23AddData :: set( const QString& key ) 24{ 25 if( Utils::isMagnetLink( key ) ) 26 { 27 magnet = key; 28 type = MAGNET; 29 } 30 else if ( Utils::isUriWithSupportedScheme( key ) ) 31 { 32 url = key; 33 type = URL; 34 } 35 else if( QFile(key).exists( ) ) 36 { 37 filename = key; 38 type = FILENAME; 39 40 QFile file( key ); 41 file.open( QIODevice::ReadOnly ); 42 metainfo = file.readAll( ); 43 file.close( ); 44 } 45 else if( Utils::isHexHashcode( key ) ) 46 { 47 magnet = QString::fromAscii("magnet:?xt=urn:btih:") + key; 48 type = MAGNET; 49 } 50 else 51 { 52 int len; 53 char * raw = tr_base64_decode( key.toUtf8().constData(), key.toUtf8().size(), &len ); 54 if( raw ) { 55 metainfo.append( raw, len ); 56 tr_free( raw ); 57 type = METAINFO; 58 } 59 else type = NONE; 60 } 61 62 return type; 63} 64 65QByteArray 66AddData :: toBase64( ) const 67{ 68 QByteArray ret; 69 70 if( !metainfo.isEmpty( ) ) 71 { 72 int len = 0; 73 char * b64 = tr_base64_encode( metainfo.constData(), metainfo.size(), &len ); 74 ret = QByteArray( b64, len ); 75 tr_free( b64 ); 76 } 77 78 return ret; 79} 80 81QString 82AddData :: readableName( ) const 83{ 84 QString ret; 85 86 switch( type ) 87 { 88 case FILENAME: ret = filename; break; 89 90 case MAGNET: ret = magnet; break; 91 92 case URL: ret = url.toString(); break; 93 94 case METAINFO: { 95 tr_info inf; 96 tr_ctor * ctor = tr_ctorNew( NULL ); 97 tr_ctorSetMetainfo( ctor, (const uint8_t*)metainfo.constData(), metainfo.size() ); 98 if( tr_torrentParse( ctor, &inf ) == TR_PARSE_OK ) { 99 ret = QString::fromUtf8( inf.name ); // metainfo is required to be UTF-8 100 tr_metainfoFree( &inf ); 101 } 102 tr_ctorFree( ctor ); 103 break; 104 } 105 } 106 107 return ret; 108} 109