1 /*
2 	*
3 	* Copyright 2018 Britanicus <marcusbritanicus@gmail.com>
4 	*
5 
6 	*
7 	* This program is free software: you can redistribute it and/or modify
8 	* it under the terms of the GNU Lesser 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 
13 	*
14 	* This program is distributed in the hope that it will be useful,
15 	* but WITHOUT ANY WARRANTY; without even the implied warranty of
16 	* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 	* GNU Lesser General Public License for more details.
18 	*
19 
20 	*
21 	* You should have received a copy of the GNU Lesser General Public License
22 	* along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 	*
24 */
25 
26 // Local Headers
27 #include <LibBZip2.hpp>
28 
29 const int MAX_READ_SIZE = 40960;
30 
31 QString NBBZip2::bz2FileName = QString();
32 QString NBBZip2::fileName = QString();
33 
NBBZip2(QString archive,QString file)34 NBBZip2::NBBZip2( QString archive, QString file ) {
35 
36 	int error = 0;
37 
38 	bz2FileName = QString( archive );
39 	if ( not file.isEmpty() ) {
40 		if ( QFileInfo( file ).isDir() ) {
41 			fileName = QDir( file ).filePath( QString( archive ) );
42 			fileName.chop( 4 );
43 		}
44 
45 		else if ( QFileInfo( file ).exists() ) {
46 			QFile::rename( file, file + ".old" );
47 			fileName = QString( file );
48 		}
49 
50 		else {
51 			fileName = QString( file );
52 		}
53 	}
54 
55 	else {
56 		fileName = QString( archive );
57 		fileName.chop( 4 );
58 	}
59 
60 	bzFile = fopen( qPrintable( bz2FileName ), "r" );
61 	bz2 = BZ2_bzReadOpen( &error, bzFile, 0, 0, NULL, 0 );
62 };
63 
extract()64 bool NBBZip2::extract() {
65 
66 	int error;
67 
68 	// Reading from the bz2 file opened
69 	std::ofstream ofile( qPrintable( fileName ), std::ofstream::binary );
70 
71 	while ( true ) {
72 		char buffer[ MAX_READ_SIZE ] = { "\x00" };
73 		int charsRead = BZ2_bzRead( &error, bz2, buffer, MAX_READ_SIZE );
74 		ofile.write( buffer, charsRead );
75 
76 		if ( error == BZ_OK )
77 			continue;
78 
79 		else
80 			break;
81 	}
82 
83 	if ( error != BZ_STREAM_END )
84 		return false;
85 
86 	// Close the file
87 	BZ2_bzReadClose( &error, bz2 );
88 
89 	if ( error != BZ_OK )
90 		return false;
91 
92 	fclose( bzFile );
93 
94 	return true;
95 };
96