Code refactor.

This commit is contained in:
2020-08-22 21:37:02 +01:00
parent b4cd7f22bf
commit 6c78f0c769
33 changed files with 5624 additions and 3480 deletions

View File

@@ -30,9 +30,7 @@ namespace apprepodbmgr.Core
{
public enum AlgoEnum
{
GZip,
BZip2,
LZMA,
GZip, BZip2, LZMA,
LZip
}
}

View File

@@ -37,41 +37,41 @@ using Schemas;
namespace apprepodbmgr.Core
{
class Checksum
internal class Checksum
{
Adler32Context adler32ctx;
adlerPacket adlerPkt;
Thread adlerThread;
Crc16Context crc16ctx;
crc16Packet crc16Pkt;
Thread crc16Thread;
Crc32Context crc32ctx;
crc32Packet crc32Pkt;
Thread crc32Thread;
Crc64Context crc64ctx;
crc64Packet crc64Pkt;
Thread crc64Thread;
Md5Context md5ctx;
md5Packet md5Pkt;
Thread md5Thread;
Ripemd160Context ripemd160ctx;
ripemd160Packet ripemd160Pkt;
Thread ripemd160Thread;
Sha1Context sha1ctx;
sha1Packet sha1Pkt;
Thread sha1Thread;
Sha256Context sha256ctx;
sha256Packet sha256Pkt;
Thread sha256Thread;
Sha384Context sha384ctx;
sha384Packet sha384Pkt;
Thread sha384Thread;
Sha512Context sha512ctx;
sha512Packet sha512Pkt;
Thread sha512Thread;
spamsumPacket spamsumPkt;
Thread spamsumThread;
SpamSumContext ssctx;
readonly Adler32Context adler32ctx;
adlerPacket adlerPkt;
Thread adlerThread;
readonly Crc16Context crc16ctx;
crc16Packet crc16Pkt;
Thread crc16Thread;
readonly Crc32Context crc32ctx;
crc32Packet crc32Pkt;
Thread crc32Thread;
readonly Crc64Context crc64ctx;
crc64Packet crc64Pkt;
Thread crc64Thread;
readonly Md5Context md5ctx;
md5Packet md5Pkt;
Thread md5Thread;
readonly Ripemd160Context ripemd160ctx;
ripemd160Packet ripemd160Pkt;
Thread ripemd160Thread;
readonly Sha1Context sha1ctx;
sha1Packet sha1Pkt;
Thread sha1Thread;
readonly Sha256Context sha256ctx;
sha256Packet sha256Pkt;
Thread sha256Thread;
readonly Sha384Context sha384ctx;
sha384Packet sha384Pkt;
Thread sha384Thread;
readonly Sha512Context sha512ctx;
sha512Packet sha512Pkt;
Thread sha512Thread;
spamsumPacket spamsumPkt;
Thread spamsumThread;
readonly SpamSumContext ssctx;
internal Checksum()
{
@@ -111,17 +111,17 @@ namespace apprepodbmgr.Core
sha512Pkt = new sha512Packet();
spamsumPkt = new spamsumPacket();
adlerPkt.context = adler32ctx;
crc16Pkt.context = crc16ctx;
crc32Pkt.context = crc32ctx;
crc64Pkt.context = crc64ctx;
md5Pkt.context = md5ctx;
adlerPkt.context = adler32ctx;
crc16Pkt.context = crc16ctx;
crc32Pkt.context = crc32ctx;
crc64Pkt.context = crc64ctx;
md5Pkt.context = md5ctx;
ripemd160Pkt.context = ripemd160ctx;
sha1Pkt.context = sha1ctx;
sha256Pkt.context = sha256ctx;
sha384Pkt.context = sha384ctx;
sha512Pkt.context = sha512ctx;
spamsumPkt.context = ssctx;
sha1Pkt.context = sha1ctx;
sha256Pkt.context = sha256ctx;
sha384Pkt.context = sha384ctx;
sha512Pkt.context = sha512ctx;
spamsumPkt.context = ssctx;
}
internal void Update(byte[] data)
@@ -149,9 +149,17 @@ namespace apprepodbmgr.Core
spamsumPkt.data = data;
spamsumThread.Start(spamsumPkt);
while(adlerThread.IsAlive || crc16Thread.IsAlive || crc32Thread.IsAlive || crc64Thread.IsAlive ||
md5Thread.IsAlive || ripemd160Thread.IsAlive || sha1Thread.IsAlive || sha256Thread.IsAlive ||
sha384Thread.IsAlive || sha512Thread.IsAlive || spamsumThread.IsAlive) { }
while(adlerThread.IsAlive ||
crc16Thread.IsAlive ||
crc32Thread.IsAlive ||
crc64Thread.IsAlive ||
md5Thread.IsAlive ||
ripemd160Thread.IsAlive ||
sha1Thread.IsAlive ||
sha256Thread.IsAlive ||
sha384Thread.IsAlive ||
sha512Thread.IsAlive ||
spamsumThread.IsAlive) {}
adlerThread = new Thread(updateAdler);
crc16Thread = new Thread(updateCRC16);
@@ -170,37 +178,92 @@ namespace apprepodbmgr.Core
{
List<ChecksumType> chks = new List<ChecksumType>();
ChecksumType chk = new ChecksumType {type = ChecksumTypeType.adler32, Value = adler32ctx.End()};
var chk = new ChecksumType
{
type = ChecksumTypeType.adler32,
Value = adler32ctx.End()
};
chks.Add(chk);
chk = new ChecksumType {type = ChecksumTypeType.crc16, Value = crc16ctx.End()};
chk = new ChecksumType
{
type = ChecksumTypeType.crc16,
Value = crc16ctx.End()
};
chks.Add(chk);
chk = new ChecksumType {type = ChecksumTypeType.crc32, Value = crc32ctx.End()};
chk = new ChecksumType
{
type = ChecksumTypeType.crc32,
Value = crc32ctx.End()
};
chks.Add(chk);
chk = new ChecksumType {type = ChecksumTypeType.crc64, Value = crc64ctx.End()};
chk = new ChecksumType
{
type = ChecksumTypeType.crc64,
Value = crc64ctx.End()
};
chks.Add(chk);
chk = new ChecksumType {type = ChecksumTypeType.md5, Value = md5ctx.End()};
chk = new ChecksumType
{
type = ChecksumTypeType.md5,
Value = md5ctx.End()
};
chks.Add(chk);
chk = new ChecksumType {type = ChecksumTypeType.ripemd160, Value = ripemd160ctx.End()};
chk = new ChecksumType
{
type = ChecksumTypeType.ripemd160,
Value = ripemd160ctx.End()
};
chks.Add(chk);
chk = new ChecksumType {type = ChecksumTypeType.sha1, Value = sha1ctx.End()};
chk = new ChecksumType
{
type = ChecksumTypeType.sha1,
Value = sha1ctx.End()
};
chks.Add(chk);
chk = new ChecksumType {type = ChecksumTypeType.sha256, Value = sha256ctx.End()};
chk = new ChecksumType
{
type = ChecksumTypeType.sha256,
Value = sha256ctx.End()
};
chks.Add(chk);
chk = new ChecksumType {type = ChecksumTypeType.sha384, Value = sha384ctx.End()};
chk = new ChecksumType
{
type = ChecksumTypeType.sha384,
Value = sha384ctx.End()
};
chks.Add(chk);
chk = new ChecksumType {type = ChecksumTypeType.sha512, Value = sha512ctx.End()};
chk = new ChecksumType
{
type = ChecksumTypeType.sha512,
Value = sha512ctx.End()
};
chks.Add(chk);
chk = new ChecksumType {type = ChecksumTypeType.spamsum, Value = ssctx.End()};
chk = new ChecksumType
{
type = ChecksumTypeType.spamsum,
Value = ssctx.End()
};
chks.Add(chk);
return chks;
@@ -208,53 +271,53 @@ namespace apprepodbmgr.Core
internal static List<ChecksumType> GetChecksums(byte[] data)
{
Adler32Context adler32ctxData = new Adler32Context();
Crc16Context crc16ctxData = new Crc16Context();
Crc32Context crc32ctxData = new Crc32Context();
Crc64Context crc64ctxData = new Crc64Context();
Md5Context md5ctxData = new Md5Context();
Ripemd160Context ripemd160ctxData = new Ripemd160Context();
Sha1Context sha1ctxData = new Sha1Context();
Sha256Context sha256ctxData = new Sha256Context();
Sha384Context sha384ctxData = new Sha384Context();
Sha512Context sha512ctxData = new Sha512Context();
SpamSumContext ssctxData = new SpamSumContext();
var adler32ctxData = new Adler32Context();
var crc16ctxData = new Crc16Context();
var crc32ctxData = new Crc32Context();
var crc64ctxData = new Crc64Context();
var md5ctxData = new Md5Context();
var ripemd160ctxData = new Ripemd160Context();
var sha1ctxData = new Sha1Context();
var sha256ctxData = new Sha256Context();
var sha384ctxData = new Sha384Context();
var sha512ctxData = new Sha512Context();
var ssctxData = new SpamSumContext();
Thread adlerThreadData = new Thread(updateAdler);
Thread crc16ThreadData = new Thread(updateCRC16);
Thread crc32ThreadData = new Thread(updateCRC32);
Thread crc64ThreadData = new Thread(updateCRC64);
Thread md5ThreadData = new Thread(updateMD5);
Thread ripemd160ThreadData = new Thread(updateRIPEMD160);
Thread sha1ThreadData = new Thread(updateSHA1);
Thread sha256ThreadData = new Thread(updateSHA256);
Thread sha384ThreadData = new Thread(updateSHA384);
Thread sha512ThreadData = new Thread(updateSHA512);
Thread spamsumThreadData = new Thread(updateSpamSum);
var adlerThreadData = new Thread(updateAdler);
var crc16ThreadData = new Thread(updateCRC16);
var crc32ThreadData = new Thread(updateCRC32);
var crc64ThreadData = new Thread(updateCRC64);
var md5ThreadData = new Thread(updateMD5);
var ripemd160ThreadData = new Thread(updateRIPEMD160);
var sha1ThreadData = new Thread(updateSHA1);
var sha256ThreadData = new Thread(updateSHA256);
var sha384ThreadData = new Thread(updateSHA384);
var sha512ThreadData = new Thread(updateSHA512);
var spamsumThreadData = new Thread(updateSpamSum);
adlerPacket adlerPktData = new adlerPacket();
crc16Packet crc16PktData = new crc16Packet();
crc32Packet crc32PktData = new crc32Packet();
crc64Packet crc64PktData = new crc64Packet();
md5Packet md5PktData = new md5Packet();
ripemd160Packet ripemd160PktData = new ripemd160Packet();
sha1Packet sha1PktData = new sha1Packet();
sha256Packet sha256PktData = new sha256Packet();
sha384Packet sha384PktData = new sha384Packet();
sha512Packet sha512PktData = new sha512Packet();
spamsumPacket spamsumPktData = new spamsumPacket();
var adlerPktData = new adlerPacket();
var crc16PktData = new crc16Packet();
var crc32PktData = new crc32Packet();
var crc64PktData = new crc64Packet();
var md5PktData = new md5Packet();
var ripemd160PktData = new ripemd160Packet();
var sha1PktData = new sha1Packet();
var sha256PktData = new sha256Packet();
var sha384PktData = new sha384Packet();
var sha512PktData = new sha512Packet();
var spamsumPktData = new spamsumPacket();
adlerPktData.context = adler32ctxData;
crc16PktData.context = crc16ctxData;
crc32PktData.context = crc32ctxData;
crc64PktData.context = crc64ctxData;
md5PktData.context = md5ctxData;
adlerPktData.context = adler32ctxData;
crc16PktData.context = crc16ctxData;
crc32PktData.context = crc32ctxData;
crc64PktData.context = crc64ctxData;
md5PktData.context = md5ctxData;
ripemd160PktData.context = ripemd160ctxData;
sha1PktData.context = sha1ctxData;
sha256PktData.context = sha256ctxData;
sha384PktData.context = sha384ctxData;
sha512PktData.context = sha512ctxData;
spamsumPktData.context = ssctxData;
sha1PktData.context = sha1ctxData;
sha256PktData.context = sha256ctxData;
sha384PktData.context = sha384ctxData;
sha512PktData.context = sha512ctxData;
spamsumPktData.context = ssctxData;
adlerPktData.data = data;
adlerThreadData.Start(adlerPktData);
@@ -279,44 +342,106 @@ namespace apprepodbmgr.Core
spamsumPktData.data = data;
spamsumThreadData.Start(spamsumPktData);
while(adlerThreadData.IsAlive || crc16ThreadData.IsAlive || crc32ThreadData.IsAlive ||
crc64ThreadData.IsAlive || md5ThreadData.IsAlive || ripemd160ThreadData.IsAlive ||
sha1ThreadData.IsAlive || sha256ThreadData.IsAlive || sha384ThreadData.IsAlive ||
sha512ThreadData.IsAlive || spamsumThreadData.IsAlive) { }
while(adlerThreadData.IsAlive ||
crc16ThreadData.IsAlive ||
crc32ThreadData.IsAlive ||
crc64ThreadData.IsAlive ||
md5ThreadData.IsAlive ||
ripemd160ThreadData.IsAlive ||
sha1ThreadData.IsAlive ||
sha256ThreadData.IsAlive ||
sha384ThreadData.IsAlive ||
sha512ThreadData.IsAlive ||
spamsumThreadData.IsAlive) {}
List<ChecksumType> dataChecksums = new List<ChecksumType>();
ChecksumType chk = new ChecksumType {type = ChecksumTypeType.adler32, Value = adler32ctxData.End()};
var chk = new ChecksumType
{
type = ChecksumTypeType.adler32,
Value = adler32ctxData.End()
};
dataChecksums.Add(chk);
chk = new ChecksumType {type = ChecksumTypeType.crc16, Value = crc16ctxData.End()};
chk = new ChecksumType
{
type = ChecksumTypeType.crc16,
Value = crc16ctxData.End()
};
dataChecksums.Add(chk);
chk = new ChecksumType {type = ChecksumTypeType.crc32, Value = crc32ctxData.End()};
chk = new ChecksumType
{
type = ChecksumTypeType.crc32,
Value = crc32ctxData.End()
};
dataChecksums.Add(chk);
chk = new ChecksumType {type = ChecksumTypeType.crc64, Value = crc64ctxData.End()};
chk = new ChecksumType
{
type = ChecksumTypeType.crc64,
Value = crc64ctxData.End()
};
dataChecksums.Add(chk);
chk = new ChecksumType {type = ChecksumTypeType.md5, Value = md5ctxData.End()};
chk = new ChecksumType
{
type = ChecksumTypeType.md5,
Value = md5ctxData.End()
};
dataChecksums.Add(chk);
chk = new ChecksumType {type = ChecksumTypeType.ripemd160, Value = ripemd160ctxData.End()};
chk = new ChecksumType
{
type = ChecksumTypeType.ripemd160,
Value = ripemd160ctxData.End()
};
dataChecksums.Add(chk);
chk = new ChecksumType {type = ChecksumTypeType.sha1, Value = sha1ctxData.End()};
chk = new ChecksumType
{
type = ChecksumTypeType.sha1,
Value = sha1ctxData.End()
};
dataChecksums.Add(chk);
chk = new ChecksumType {type = ChecksumTypeType.sha256, Value = sha256ctxData.End()};
chk = new ChecksumType
{
type = ChecksumTypeType.sha256,
Value = sha256ctxData.End()
};
dataChecksums.Add(chk);
chk = new ChecksumType {type = ChecksumTypeType.sha384, Value = sha384ctxData.End()};
chk = new ChecksumType
{
type = ChecksumTypeType.sha384,
Value = sha384ctxData.End()
};
dataChecksums.Add(chk);
chk = new ChecksumType {type = ChecksumTypeType.sha512, Value = sha512ctxData.End()};
chk = new ChecksumType
{
type = ChecksumTypeType.sha512,
Value = sha512ctxData.End()
};
dataChecksums.Add(chk);
chk = new ChecksumType {type = ChecksumTypeType.spamsum, Value = ssctxData.End()};
chk = new ChecksumType
{
type = ChecksumTypeType.spamsum,
Value = ssctxData.End()
};
dataChecksums.Add(chk);
return dataChecksums;
@@ -389,60 +514,29 @@ namespace apprepodbmgr.Core
public byte[] data;
}
static void updateAdler(object packet)
{
((adlerPacket)packet).context.Update(((adlerPacket)packet).data);
}
static void updateAdler(object packet) => ((adlerPacket)packet).context.Update(((adlerPacket)packet).data);
static void updateCRC16(object packet)
{
((crc16Packet)packet).context.Update(((crc16Packet)packet).data);
}
static void updateCRC16(object packet) => ((crc16Packet)packet).context.Update(((crc16Packet)packet).data);
static void updateCRC32(object packet)
{
((crc32Packet)packet).context.Update(((crc32Packet)packet).data);
}
static void updateCRC32(object packet) => ((crc32Packet)packet).context.Update(((crc32Packet)packet).data);
static void updateCRC64(object packet)
{
((crc64Packet)packet).context.Update(((crc64Packet)packet).data);
}
static void updateCRC64(object packet) => ((crc64Packet)packet).context.Update(((crc64Packet)packet).data);
static void updateMD5(object packet)
{
((md5Packet)packet).context.Update(((md5Packet)packet).data);
}
static void updateMD5(object packet) => ((md5Packet)packet).context.Update(((md5Packet)packet).data);
static void updateRIPEMD160(object packet)
{
static void updateRIPEMD160(object packet) =>
((ripemd160Packet)packet).context.Update(((ripemd160Packet)packet).data);
}
static void updateSHA1(object packet)
{
((sha1Packet)packet).context.Update(((sha1Packet)packet).data);
}
static void updateSHA1(object packet) => ((sha1Packet)packet).context.Update(((sha1Packet)packet).data);
static void updateSHA256(object packet)
{
((sha256Packet)packet).context.Update(((sha256Packet)packet).data);
}
static void updateSHA256(object packet) => ((sha256Packet)packet).context.Update(((sha256Packet)packet).data);
static void updateSHA384(object packet)
{
((sha384Packet)packet).context.Update(((sha384Packet)packet).data);
}
static void updateSHA384(object packet) => ((sha384Packet)packet).context.Update(((sha384Packet)packet).data);
static void updateSHA512(object packet)
{
((sha512Packet)packet).context.Update(((sha512Packet)packet).data);
}
static void updateSHA512(object packet) => ((sha512Packet)packet).context.Update(((sha512Packet)packet).data);
static void updateSpamSum(object packet)
{
static void updateSpamSum(object packet) =>
((spamsumPacket)packet).context.Update(((spamsumPacket)packet).data);
}
#endregion Threading helpers
}
}

View File

@@ -68,7 +68,7 @@ namespace apprepodbmgr.Core
Workers.FinishedWithText += CheckUnarFinished;
Workers.Failed += CheckUnarFailed;
Thread thdCheckUnar = new Thread(Workers.CheckUnar);
var thdCheckUnar = new Thread(Workers.CheckUnar);
thdCheckUnar.Start();
}

View File

@@ -111,14 +111,14 @@ namespace apprepodbmgr.Core
IDbCommand dbcmd = dbCon.CreateCommand();
IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter();
dbcmd.CommandText = SQL;
DataSet dataSet = new DataSet();
var dataSet = new DataSet();
dataAdapter.SelectCommand = dbcmd;
dataAdapter.Fill(dataSet);
DataTable dataTable = dataSet.Tables[0];
foreach(DataRow dRow in dataTable.Rows)
{
DbEntry fEntry = new DbEntry
var fEntry = new DbEntry
{
Id = long.Parse(dRow["id"].ToString()),
Developer = dRow["developer"].ToString(),
@@ -138,9 +138,15 @@ namespace apprepodbmgr.Core
Mdid = dRow["mdid"].ToString()
};
if(dRow["xml"] != DBNull.Value) fEntry.Xml = (byte[])dRow["xml"];
if(dRow["json"] != DBNull.Value) fEntry.Json = (byte[])dRow["json"];
if(dRow["icon"] != DBNull.Value) fEntry.Icon = (byte[])dRow["icon"];
if(dRow["xml"] != DBNull.Value)
fEntry.Xml = (byte[])dRow["xml"];
if(dRow["json"] != DBNull.Value)
fEntry.Json = (byte[])dRow["json"];
if(dRow["icon"] != DBNull.Value)
fEntry.Icon = (byte[])dRow["icon"];
entries.Add(fEntry);
}
@@ -363,13 +369,14 @@ namespace apprepodbmgr.Core
param1.Value = hash;
dbcmd.Parameters.Add(param1);
dbcmd.CommandText = "SELECT * FROM files WHERE sha256 = @hash";
DataSet dataSet = new DataSet();
var dataSet = new DataSet();
IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter();
dataAdapter.SelectCommand = dbcmd;
dataAdapter.Fill(dataSet);
DataTable dataTable = dataSet.Tables[0];
foreach(DataRow dRow in dataTable.Rows) return true;
foreach(DataRow dRow in dataTable.Rows)
return true;
return false;
}
@@ -380,8 +387,15 @@ namespace apprepodbmgr.Core
dbcmd.CommandText = "SELECT COUNT(*) FROM files";
object count = dbcmd.ExecuteScalar();
dbcmd.Dispose();
try { return Convert.ToUInt64(count); }
catch { return 0; }
try
{
return Convert.ToUInt64(count);
}
catch
{
return 0;
}
}
public DbFile GetFile(string hash)
@@ -391,14 +405,14 @@ namespace apprepodbmgr.Core
IDbCommand dbcmd = dbCon.CreateCommand();
IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter();
dbcmd.CommandText = sql;
DataSet dataSet = new DataSet();
var dataSet = new DataSet();
dataAdapter.SelectCommand = dbcmd;
dataAdapter.Fill(dataSet);
DataTable dataTable = dataSet.Tables[0];
foreach(DataRow dRow in dataTable.Rows)
{
DbFile fEntry = new DbFile
var fEntry = new DbFile
{
Id = ulong.Parse(dRow["id"].ToString()),
Sha256 = dRow["sha256"].ToString(),
@@ -407,14 +421,20 @@ namespace apprepodbmgr.Core
Length = long.Parse(dRow["length"].ToString())
};
if(dRow["hasvirus"] == DBNull.Value) fEntry.HasVirus = null;
else fEntry.HasVirus = bool.Parse(dRow["hasvirus"].ToString());
if(dRow["clamtime"] == DBNull.Value) fEntry.ClamTime = null;
else fEntry.ClamTime = DateTime.Parse(dRow["clamtime"].ToString());
if(dRow["vtotaltime"] == DBNull.Value) fEntry.VirusTotalTime = null;
if(dRow["hasvirus"] == DBNull.Value)
fEntry.HasVirus = null;
else
fEntry.VirusTotalTime =
DateTime.Parse(dRow["vtotaltime"].ToString());
fEntry.HasVirus = bool.Parse(dRow["hasvirus"].ToString());
if(dRow["clamtime"] == DBNull.Value)
fEntry.ClamTime = null;
else
fEntry.ClamTime = DateTime.Parse(dRow["clamtime"].ToString());
if(dRow["vtotaltime"] == DBNull.Value)
fEntry.VirusTotalTime = null;
else
fEntry.VirusTotalTime = DateTime.Parse(dRow["vtotaltime"].ToString());
return fEntry;
}
@@ -431,14 +451,14 @@ namespace apprepodbmgr.Core
IDbCommand dbcmd = dbCon.CreateCommand();
IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter();
dbcmd.CommandText = sql;
DataSet dataSet = new DataSet();
var dataSet = new DataSet();
dataAdapter.SelectCommand = dbcmd;
dataAdapter.Fill(dataSet);
DataTable dataTable = dataSet.Tables[0];
foreach(DataRow dRow in dataTable.Rows)
{
DbFile fEntry = new DbFile
var fEntry = new DbFile
{
Id = ulong.Parse(dRow["id"].ToString()),
Sha256 = dRow["sha256"].ToString(),
@@ -447,14 +467,20 @@ namespace apprepodbmgr.Core
Length = long.Parse(dRow["length"].ToString())
};
if(dRow["hasvirus"] == DBNull.Value) fEntry.HasVirus = null;
else fEntry.HasVirus = bool.Parse(dRow["hasvirus"].ToString());
if(dRow["clamtime"] == DBNull.Value) fEntry.ClamTime = null;
else fEntry.ClamTime = DateTime.Parse(dRow["clamtime"].ToString());
if(dRow["vtotaltime"] == DBNull.Value) fEntry.VirusTotalTime = null;
if(dRow["hasvirus"] == DBNull.Value)
fEntry.HasVirus = null;
else
fEntry.VirusTotalTime =
DateTime.Parse(dRow["vtotaltime"].ToString());
fEntry.HasVirus = bool.Parse(dRow["hasvirus"].ToString());
if(dRow["clamtime"] == DBNull.Value)
fEntry.ClamTime = null;
else
fEntry.ClamTime = DateTime.Parse(dRow["clamtime"].ToString());
if(dRow["vtotaltime"] == DBNull.Value)
fEntry.VirusTotalTime = null;
else
fEntry.VirusTotalTime = DateTime.Parse(dRow["vtotaltime"].ToString());
entries.Add(fEntry);
}
@@ -471,14 +497,14 @@ namespace apprepodbmgr.Core
IDbCommand dbcmd = dbCon.CreateCommand();
IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter();
dbcmd.CommandText = SQL;
DataSet dataSet = new DataSet();
var dataSet = new DataSet();
dataAdapter.SelectCommand = dbcmd;
dataAdapter.Fill(dataSet);
DataTable dataTable = dataSet.Tables[0];
foreach(DataRow dRow in dataTable.Rows)
{
DbFile fEntry = new DbFile
var fEntry = new DbFile
{
Id = ulong.Parse(dRow["id"].ToString()),
Sha256 = dRow["sha256"].ToString(),
@@ -487,14 +513,20 @@ namespace apprepodbmgr.Core
Length = long.Parse(dRow["length"].ToString())
};
if(dRow["hasvirus"] == DBNull.Value) fEntry.HasVirus = null;
else fEntry.HasVirus = bool.Parse(dRow["hasvirus"].ToString());
if(dRow["clamtime"] == DBNull.Value) fEntry.ClamTime = null;
else fEntry.ClamTime = DateTime.Parse(dRow["clamtime"].ToString());
if(dRow["vtotaltime"] == DBNull.Value) fEntry.VirusTotalTime = null;
if(dRow["hasvirus"] == DBNull.Value)
fEntry.HasVirus = null;
else
fEntry.VirusTotalTime =
DateTime.Parse(dRow["vtotaltime"].ToString());
fEntry.HasVirus = bool.Parse(dRow["hasvirus"].ToString());
if(dRow["clamtime"] == DBNull.Value)
fEntry.ClamTime = null;
else
fEntry.ClamTime = DateTime.Parse(dRow["clamtime"].ToString());
if(dRow["vtotaltime"] == DBNull.Value)
fEntry.VirusTotalTime = null;
else
fEntry.VirusTotalTime = DateTime.Parse(dRow["vtotaltime"].ToString());
entries.Add(fEntry);
}
@@ -683,16 +715,11 @@ namespace apprepodbmgr.Core
IDbTransaction trans = dbCon.BeginTransaction();
dbcmd.Transaction = trans;
string sql = $"DROP TABLE IF EXISTS `app_{id}`;\n\n" +
$"CREATE TABLE IF NOT EXISTS `app_{id}` (\n" +
" `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" `path` VARCHAR(8192) NOT NULL,\n" +
" `sha256` VARCHAR(64) NOT NULL,\n\n" +
" `length` BIGINT NOT NULL,\n" +
" `creation` DATETIME NULL,\n" +
" `access` DATETIME NULL,\n" +
" `modification` DATETIME NULL,\n" +
" `attributes` INTEGER NULL);\n\n" +
string sql = $"DROP TABLE IF EXISTS `app_{id}`;\n\n" + $"CREATE TABLE IF NOT EXISTS `app_{id}` (\n" +
" `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" + " `path` VARCHAR(8192) NOT NULL,\n" +
" `sha256` VARCHAR(64) NOT NULL,\n\n" + " `length` BIGINT NOT NULL,\n" +
" `creation` DATETIME NULL,\n" + " `access` DATETIME NULL,\n" +
" `modification` DATETIME NULL,\n" + " `attributes` INTEGER NULL);\n\n" +
$"CREATE UNIQUE INDEX `app_{id}_id_UNIQUE` ON `app_{id}` (`id` ASC);\n\n" +
$"CREATE INDEX `app_{id}_path_idx` ON `app_{id}` (`path` ASC);";
@@ -706,14 +733,11 @@ namespace apprepodbmgr.Core
trans = dbCon.BeginTransaction();
dbcmd.Transaction = trans;
sql = $"DROP TABLE IF EXISTS `app_{id}_folders`;\n\n" +
$"CREATE TABLE IF NOT EXISTS `app_{id}_folders` (\n" +
" `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" `path` VARCHAR(8192) NOT NULL,\n" +
" `creation` DATETIME NULL,\n" +
" `access` DATETIME NULL,\n" +
" `modification` DATETIME NULL,\n" +
" `attributes` INTEGER NULL);\n\n" +
sql = $"DROP TABLE IF EXISTS `app_{id}_folders`;\n\n" +
$"CREATE TABLE IF NOT EXISTS `app_{id}_folders` (\n" + " `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" `path` VARCHAR(8192) NOT NULL,\n" + " `creation` DATETIME NULL,\n" +
" `access` DATETIME NULL,\n" + " `modification` DATETIME NULL,\n" +
" `attributes` INTEGER NULL);\n\n" +
$"CREATE UNIQUE INDEX `app_{id}_folders_id_UNIQUE` ON `app_{id}_folders` (`id` ASC);\n\n" +
$"CREATE INDEX `app_{id}_folders_path_idx` ON `app_{id}_folders` (`path` ASC);";
@@ -736,13 +760,14 @@ namespace apprepodbmgr.Core
param1.Value = hash;
dbcmd.Parameters.Add(param1);
dbcmd.CommandText = $"SELECT * FROM `app_{appId}` WHERE sha256 = @hash";
DataSet dataSet = new DataSet();
var dataSet = new DataSet();
IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter();
dataAdapter.SelectCommand = dbcmd;
dataAdapter.Fill(dataSet);
DataTable dataTable = dataSet.Tables[0];
foreach(DataRow dRow in dataTable.Rows) return true;
foreach(DataRow dRow in dataTable.Rows)
return true;
return false;
}
@@ -757,13 +782,14 @@ namespace apprepodbmgr.Core
param1.Value = mdid;
dbcmd.Parameters.Add(param1);
dbcmd.CommandText = "SELECT * FROM `apps` WHERE mdid = @mdid";
DataSet dataSet = new DataSet();
var dataSet = new DataSet();
IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter();
dataAdapter.SelectCommand = dbcmd;
dataAdapter.Fill(dataSet);
DataTable dataTable = dataSet.Tables[0];
foreach(DataRow dRow in dataTable.Rows) return true;
foreach(DataRow dRow in dataTable.Rows)
return true;
return false;
}
@@ -777,14 +803,14 @@ namespace apprepodbmgr.Core
IDbCommand dbcmd = dbCon.CreateCommand();
IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter();
dbcmd.CommandText = sql;
DataSet dataSet = new DataSet();
var dataSet = new DataSet();
dataAdapter.SelectCommand = dbcmd;
dataAdapter.Fill(dataSet);
DataTable dataTable = dataSet.Tables[0];
foreach(DataRow dRow in dataTable.Rows)
{
DbAppFile fEntry = new DbAppFile
var fEntry = new DbAppFile
{
Id = ulong.Parse(dRow["id"].ToString()),
Path = dRow["path"].ToString(),
@@ -811,14 +837,14 @@ namespace apprepodbmgr.Core
IDbCommand dbcmd = dbCon.CreateCommand();
IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter();
dbcmd.CommandText = sql;
DataSet dataSet = new DataSet();
var dataSet = new DataSet();
dataAdapter.SelectCommand = dbcmd;
dataAdapter.Fill(dataSet);
DataTable dataTable = dataSet.Tables[0];
foreach(DataRow dRow in dataTable.Rows)
{
DbFolder fEntry = new DbFolder
var fEntry = new DbFolder
{
Id = ulong.Parse(dRow["id"].ToString()),
Path = dRow["path"].ToString(),
@@ -875,8 +901,10 @@ namespace apprepodbmgr.Core
public bool HasSymlinks(long appId)
{
IDbCommand dbcmd = dbCon.CreateCommand();
dbcmd.CommandText =
$"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'app_{appId}_symlinks'";
object count = dbcmd.ExecuteScalar();
dbcmd.Dispose();
@@ -889,13 +917,11 @@ namespace apprepodbmgr.Core
IDbTransaction trans = dbCon.BeginTransaction();
dbcmd.Transaction = trans;
dbcmd.CommandText =
$"DROP TABLE IF EXISTS `app_{id}_symlinks`;\n\n" +
$"CREATE TABLE IF NOT EXISTS `app_{id}_symlinks` (\n" +
" `path` VARCHAR(8192) PRIMARY KEY,\n" +
" `target` VARCHAR(8192) NOT NULL);\n\n" +
$"CREATE UNIQUE INDEX `app_{id}_symlinks_path_UNIQUE` ON `app_{id}_symlinks` (`path` ASC);\n\n" +
$"CREATE INDEX `app_{id}_symlinks_target_idx` ON `app_{id}_symlinks` (`target` ASC);";
dbcmd.CommandText = $"DROP TABLE IF EXISTS `app_{id}_symlinks`;\n\n" +
$"CREATE TABLE IF NOT EXISTS `app_{id}_symlinks` (\n" +
" `path` VARCHAR(8192) PRIMARY KEY,\n" + " `target` VARCHAR(8192) NOT NULL);\n\n" +
$"CREATE UNIQUE INDEX `app_{id}_symlinks_path_UNIQUE` ON `app_{id}_symlinks` (`path` ASC);\n\n" +
$"CREATE INDEX `app_{id}_symlinks_target_idx` ON `app_{id}_symlinks` (`target` ASC);";
dbcmd.ExecuteNonQuery();
trans.Commit();
@@ -946,7 +972,7 @@ namespace apprepodbmgr.Core
IDbCommand dbcmd = dbCon.CreateCommand();
IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter();
dbcmd.CommandText = sql;
DataSet dataSet = new DataSet();
var dataSet = new DataSet();
dataAdapter.SelectCommand = dbcmd;
dataAdapter.Fill(dataSet);
DataTable dataTable = dataSet.Tables[0];

View File

@@ -43,7 +43,7 @@ namespace apprepodbmgr.Core
{
try
{
PluginBase plugins = new PluginBase();
var plugins = new PluginBase();
IMediaImage imageFormat = null;
@@ -53,37 +53,45 @@ namespace apprepodbmgr.Core
)
try
{
if(!imageplugin.Identify(imageFilter)) continue;
if(!imageplugin.Identify(imageFilter))
continue;
imageFormat = imageplugin;
break;
}
#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body
catch { }
catch {}
#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body
// Check only RAW plugin
if(imageFormat != null) return imageFormat;
if(imageFormat != null)
return imageFormat;
foreach(IMediaImage imageplugin in
plugins.ImagePluginsList.Values.Where(p => p.Id == new Guid("12345678-AAAA-BBBB-CCCC-123456789000"))
)
try
{
if(!imageplugin.Identify(imageFilter)) continue;
if(!imageplugin.Identify(imageFilter))
continue;
imageFormat = imageplugin;
break;
}
#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body
catch { }
catch {}
#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body
// Still not recognized
return imageFormat;
}
catch { return null; }
catch
{
return null;
}
}
}
}

View File

@@ -51,27 +51,31 @@ namespace DiscImageChef.Interop
public static PlatformID GetRealPlatformID()
{
if((int)Environment.OSVersion.Platform < 4 || (int)Environment.OSVersion.Platform == 5)
if((int)Environment.OSVersion.Platform < 4 ||
(int)Environment.OSVersion.Platform == 5)
return (PlatformID)(int)Environment.OSVersion.Platform;
int error = uname(out utsname unixname);
if(error != 0) throw new Exception($"Unhandled exception calling uname: {Marshal.GetLastWin32Error()}");
if(error != 0)
throw new Exception($"Unhandled exception calling uname: {Marshal.GetLastWin32Error()}");
switch(unixname.sysname)
{
// TODO: Differentiate Linux, Android, Tizen
case "Linux":
{
#if __ANDROID__
#if __ANDROID__
return PlatformID.Android;
#else
#else
return PlatformID.Linux;
#endif
#endif
}
case "Darwin":
{
IntPtr pLen = Marshal.AllocHGlobal(sizeof(int));
int osx_error = OSX_sysctlbyname("hw.machine", IntPtr.Zero, pLen, IntPtr.Zero, 0);
if(osx_error != 0)
{
Marshal.FreeHGlobal(pLen);
@@ -81,7 +85,8 @@ namespace DiscImageChef.Interop
int length = Marshal.ReadInt32(pLen);
IntPtr pStr = Marshal.AllocHGlobal(length);
osx_error = OSX_sysctlbyname("hw.machine", pStr, pLen, IntPtr.Zero, 0);
osx_error = OSX_sysctlbyname("hw.machine", pStr, pLen, IntPtr.Zero, 0);
if(osx_error != 0)
{
Marshal.FreeHGlobal(pStr);
@@ -95,22 +100,23 @@ namespace DiscImageChef.Interop
Marshal.FreeHGlobal(pStr);
Marshal.FreeHGlobal(pLen);
if(machine.StartsWith("iPad", StringComparison.Ordinal) ||
machine.StartsWith("iPod", StringComparison.Ordinal) ||
machine.StartsWith("iPhone", StringComparison.Ordinal)) return PlatformID.iOS;
if(machine.StartsWith("iPad", StringComparison.Ordinal) ||
machine.StartsWith("iPod", StringComparison.Ordinal) ||
machine.StartsWith("iPhone", StringComparison.Ordinal))
return PlatformID.iOS;
return PlatformID.MacOSX;
}
case "GNU": return PlatformID.Hurd;
case "FreeBSD":
case "GNU/kFreeBSD": return PlatformID.FreeBSD;
case "DragonFly": return PlatformID.DragonFly;
case "Haiku": return PlatformID.Haiku;
case "HP-UX": return PlatformID.HPUX;
case "AIX": return PlatformID.AIX;
case "OS400": return PlatformID.OS400;
case "DragonFly": return PlatformID.DragonFly;
case "Haiku": return PlatformID.Haiku;
case "HP-UX": return PlatformID.HPUX;
case "AIX": return PlatformID.AIX;
case "OS400": return PlatformID.OS400;
case "IRIX":
case "IRIX64": return PlatformID.IRIX;
case "IRIX64": return PlatformID.IRIX;
case "Minix": return PlatformID.Minix;
case "NetBSD": return PlatformID.NetBSD;
case "NONSTOP_KERNEL": return PlatformID.NonStop;
@@ -126,63 +132,42 @@ namespace DiscImageChef.Interop
case "UWIN-W7": return PlatformID.Win32NT;
default:
{
if(unixname.sysname.StartsWith("CYGWIN_NT", StringComparison.Ordinal) ||
if(unixname.sysname.StartsWith("CYGWIN_NT", StringComparison.Ordinal) ||
unixname.sysname.StartsWith("MINGW32_NT", StringComparison.Ordinal) ||
unixname.sysname.StartsWith("MSYS_NT", StringComparison.Ordinal) ||
unixname.sysname.StartsWith("UWIN", StringComparison.Ordinal)) return PlatformID.Win32NT;
unixname.sysname.StartsWith("MSYS_NT", StringComparison.Ordinal) ||
unixname.sysname.StartsWith("UWIN", StringComparison.Ordinal))
return PlatformID.Win32NT;
return PlatformID.Unknown;
}
}
}
/// <summary>
/// Checks if the underlying runtime runs in 64-bit mode
/// </summary>
public static bool Is64Bit()
{
return IntPtr.Size == 8;
}
/// <summary>Checks if the underlying runtime runs in 64-bit mode</summary>
public static bool Is64Bit() => IntPtr.Size == 8;
/// <summary>
/// Checks if the underlying runtime runs in 32-bit mode
/// </summary>
public static bool Is32Bit()
{
return IntPtr.Size == 4;
}
/// <summary>Checks if the underlying runtime runs in 32-bit mode</summary>
public static bool Is32Bit() => IntPtr.Size == 4;
/// <summary>
/// POSIX uname structure, size from OSX, big enough to handle extra fields
/// </summary>
/// <summary>POSIX uname structure, size from OSX, big enough to handle extra fields</summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
struct utsname
{
/// <summary>
/// System name
/// </summary>
/// <summary>System name</summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string sysname;
/// <summary>
/// Node name
/// </summary>
public readonly string sysname;
/// <summary>Node name</summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string nodename;
/// <summary>
/// Release level
/// </summary>
public readonly string nodename;
/// <summary>Release level</summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string release;
/// <summary>
/// Version level
/// </summary>
public readonly string release;
/// <summary>Version level</summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string version;
/// <summary>
/// Hardware level
/// </summary>
public readonly string version;
/// <summary>Hardware level</summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string machine;
public readonly string machine;
}
}
}

View File

@@ -6,28 +6,32 @@ namespace apprepodbmgr.Core
{
public static class IO
{
public static List<string> EnumerateFiles(string path, string searchPattern,
SearchOption searchOption,
bool followLinks = true, bool symlinks = true)
public static List<string> EnumerateFiles(string path, string searchPattern, SearchOption searchOption,
bool followLinks = true, bool symlinks = true)
{
if(followLinks) return new List<string>(Directory.EnumerateFiles(path, searchPattern, searchOption));
if(followLinks)
return new List<string>(Directory.EnumerateFiles(path, searchPattern, searchOption));
List<string> files = new List<string>();
List<string> directories = new List<string>();
foreach(string file in Directory.EnumerateFiles(path, searchPattern))
{
FileInfo fi = new FileInfo(file);
if(fi.Attributes.HasFlag(FileAttributes.ReparsePoint) && symlinks) files.Add(file);
var fi = new FileInfo(file);
if(fi.Attributes.HasFlag(FileAttributes.ReparsePoint) && symlinks)
files.Add(file);
else if(!fi.Attributes.HasFlag(FileAttributes.ReparsePoint))
files.Add(file);
}
if(searchOption != SearchOption.AllDirectories) return files;
if(searchOption != SearchOption.AllDirectories)
return files;
foreach(string directory in Directory.EnumerateDirectories(path, searchPattern))
{
DirectoryInfo di = new DirectoryInfo(directory);
var di = new DirectoryInfo(directory);
if(!di.Attributes.HasFlag(FileAttributes.ReparsePoint))
files.AddRange(EnumerateFiles(directory, searchPattern, searchOption, followLinks, symlinks));
}
@@ -35,20 +39,20 @@ namespace apprepodbmgr.Core
return files;
}
public static List<string> EnumerateDirectories(string path, string searchPattern,
SearchOption searchOption,
bool followLinks = true, bool symlinks = true)
public static List<string> EnumerateDirectories(string path, string searchPattern, SearchOption searchOption,
bool followLinks = true, bool symlinks = true)
{
if(followLinks) return new List<string>(Directory.EnumerateDirectories(path, searchPattern, searchOption));
if(followLinks)
return new List<string>(Directory.EnumerateDirectories(path, searchPattern, searchOption));
List<string> directories = new List<string>();
if(searchOption != SearchOption.AllDirectories) return directories;
if(searchOption != SearchOption.AllDirectories)
return directories;
directories.AddRange(from directory in Directory.EnumerateDirectories(path, searchPattern)
let di = new DirectoryInfo(directory)
where !di.Attributes.HasFlag(FileAttributes.ReparsePoint)
select directory);
directories.AddRange(from directory in Directory.EnumerateDirectories(path, searchPattern) let di =
new DirectoryInfo(directory)
where !di.Attributes.HasFlag(FileAttributes.ReparsePoint) select directory);
List<string> newDirectories = new List<string>();
@@ -65,17 +69,18 @@ namespace apprepodbmgr.Core
{
List<string> directories = new List<string>();
List<string> links = (from file in Directory.EnumerateFiles(path, searchPattern)
let fi = new FileInfo(file)
where fi.Attributes.HasFlag(FileAttributes.ReparsePoint)
select file).ToList();
List<string> links = (from file in Directory.EnumerateFiles(path, searchPattern) let fi = new FileInfo(file)
where fi.Attributes.HasFlag(FileAttributes.ReparsePoint) select file).ToList();
if(searchOption != SearchOption.AllDirectories) return links;
if(searchOption != SearchOption.AllDirectories)
return links;
foreach(string directory in Directory.EnumerateDirectories(path, searchPattern))
{
DirectoryInfo di = new DirectoryInfo(directory);
if(!di.Attributes.HasFlag(FileAttributes.ReparsePoint)) directories.Add(directory);
var di = new DirectoryInfo(directory);
if(!di.Attributes.HasFlag(FileAttributes.ReparsePoint))
directories.Add(directory);
else //if (!links.Contains(directory))
links.Add(directory);
}

View File

@@ -40,150 +40,77 @@ namespace DiscImageChef.Interop
{
public enum PlatformID
{
/// <summary>
/// Win32s
/// </summary>
/// <summary>Win32s</summary>
Win32S = 0,
/// <summary>
/// Win32 (Windows 9x)
/// </summary>
/// <summary>Win32 (Windows 9x)</summary>
Win32Windows = 1,
/// <summary>
/// Windows NT
/// </summary>
/// <summary>Windows NT</summary>
Win32NT = 2,
/// <summary>
/// Windows Mobile
/// </summary>
/// <summary>Windows Mobile</summary>
WinCE = 3,
/// <summary>
/// UNIX (do not use, too generic)
/// </summary>
/// <summary>UNIX (do not use, too generic)</summary>
Unix = 4,
/// <summary>
/// Xbox 360
/// </summary>
/// <summary>Xbox 360</summary>
Xbox = 5,
/// <summary>
/// OS X
/// </summary>
/// <summary>OS X</summary>
MacOSX = 6,
/// <summary>
/// iOS is not OS X
/// </summary>
/// <summary>iOS is not OS X</summary>
iOS = 7,
/// <summary>
/// Linux
/// </summary>
/// <summary>Linux</summary>
Linux = 8,
/// <summary>
/// Sun Solaris
/// </summary>
/// <summary>Sun Solaris</summary>
Solaris = 9,
/// <summary>
/// NetBSD
/// </summary>
/// <summary>NetBSD</summary>
NetBSD = 10,
/// <summary>
/// OpenBSD
/// </summary>
/// <summary>OpenBSD</summary>
OpenBSD = 11,
/// <summary>
/// FreeBSD
/// </summary>
/// <summary>FreeBSD</summary>
FreeBSD = 12,
/// <summary>
/// DragonFly BSD
/// </summary>
/// <summary>DragonFly BSD</summary>
DragonFly = 13,
/// <summary>
/// Nintendo Wii
/// </summary>
/// <summary>Nintendo Wii</summary>
Wii = 14,
/// <summary>
/// Nintendo Wii U
/// </summary>
/// <summary>Nintendo Wii U</summary>
WiiU = 15,
/// <summary>
/// Sony PlayStation 3
/// </summary>
/// <summary>Sony PlayStation 3</summary>
PlayStation3 = 16,
/// <summary>
/// Sony Playstation 4
/// </summary>
/// <summary>Sony Playstation 4</summary>
PlayStation4 = 17,
/// <summary>
/// Google Android
/// </summary>
/// <summary>Google Android</summary>
Android = 18,
/// <summary>
/// Samsung Tizen
/// </summary>
/// <summary>Samsung Tizen</summary>
Tizen = 19,
/// <summary>
/// Windows Phone
/// </summary>
/// <summary>Windows Phone</summary>
WindowsPhone = 20,
/// <summary>
/// GNU/Hurd
/// </summary>
/// <summary>GNU/Hurd</summary>
Hurd = 21,
/// <summary>
/// Haiku
/// </summary>
/// <summary>Haiku</summary>
Haiku = 22,
/// <summary>
/// HP-UX
/// </summary>
/// <summary>HP-UX</summary>
HPUX = 23,
/// <summary>
/// AIX
/// </summary>
/// <summary>AIX</summary>
AIX = 24,
/// <summary>
/// OS/400
/// </summary>
/// <summary>OS/400</summary>
OS400 = 25,
/// <summary>
/// IRIX
/// </summary>
/// <summary>IRIX</summary>
IRIX = 26,
/// <summary>
/// Minix
/// </summary>
/// <summary>Minix</summary>
Minix = 27,
/// <summary>
/// NonStop
/// </summary>
/// <summary>NonStop</summary>
NonStop = 28,
/// <summary>
/// QNX
/// </summary>
/// <summary>QNX</summary>
QNX = 29,
/// <summary>
/// SINIX
/// </summary>
/// <summary>SINIX</summary>
SINIX = 30,
/// <summary>
/// Tru64 UNIX
/// </summary>
/// <summary>Tru64 UNIX</summary>
Tru64 = 31,
/// <summary>
/// Ultrix
/// </summary>
/// <summary>Ultrix</summary>
Ultrix = 32,
/// <summary>
/// SCO OpenServer / SCO UNIX
/// </summary>
/// <summary>SCO OpenServer / SCO UNIX</summary>
OpenServer = 33,
/// <summary>
/// SCO UnixWare
/// </summary>
/// <summary>SCO UnixWare</summary>
UnixWare = 34,
/// <summary>
/// IBM z/OS
/// </summary>
zOS = 35,
Unknown = -1
/// <summary>IBM z/OS</summary>
zOS = 35, Unknown = -1
}
}

View File

@@ -40,35 +40,21 @@ using DiscImageChef.Partitions;
namespace apprepodbmgr.Core
{
/// <summary>
/// Contain all plugins (filesystem, partition and image)
/// </summary>
/// <summary>Contain all plugins (filesystem, partition and image)</summary>
public class PluginBase
{
/// <summary>
/// List of all media image plugins
/// </summary>
/// <summary>List of all media image plugins</summary>
public readonly SortedDictionary<string, IMediaImage> ImagePluginsList;
/// <summary>
/// List of all partition plugins
/// </summary>
/// <summary>List of all partition plugins</summary>
public readonly SortedDictionary<string, IPartition> PartPluginsList;
/// <summary>
/// List of all filesystem plugins
/// </summary>
/// <summary>List of all filesystem plugins</summary>
public readonly SortedDictionary<string, IFilesystem> PluginsList;
/// <summary>
/// List of read-only filesystem plugins
/// </summary>
/// <summary>List of read-only filesystem plugins</summary>
public readonly SortedDictionary<string, IReadOnlyFilesystem> ReadOnlyFilesystems;
/// <summary>
/// List of writable media image plugins
/// </summary>
/// <summary>List of writable media image plugins</summary>
public readonly SortedDictionary<string, IWritableImage> WritableImages;
/// <summary>
/// Initializes the plugins lists
/// </summary>
/// <summary>Initializes the plugins lists</summary>
public PluginBase()
{
PluginsList = new SortedDictionary<string, IFilesystem>();
@@ -77,62 +63,86 @@ namespace apprepodbmgr.Core
ImagePluginsList = new SortedDictionary<string, IMediaImage>();
WritableImages = new SortedDictionary<string, IWritableImage>();
Assembly assembly = Assembly.GetAssembly(typeof(IMediaImage));
var assembly = Assembly.GetAssembly(typeof(IMediaImage));
foreach(Type type in assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IMediaImage)))
.Where(t => t.IsClass))
foreach(Type type in assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IMediaImage))).
Where(t => t.IsClass))
try
{
IMediaImage plugin = (IMediaImage)type.GetConstructor(Type.EmptyTypes)?.Invoke(new object[] { });
var plugin = (IMediaImage)type.GetConstructor(Type.EmptyTypes)?.Invoke(new object[]
{});
RegisterImagePlugin(plugin);
}
catch(Exception exception) { Console.WriteLine("Exception {0}", exception); }
catch(Exception exception)
{
Console.WriteLine("Exception {0}", exception);
}
assembly = Assembly.GetAssembly(typeof(IPartition));
foreach(Type type in assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IPartition)))
.Where(t => t.IsClass))
foreach(Type type in assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IPartition))).
Where(t => t.IsClass))
try
{
IPartition plugin = (IPartition)type.GetConstructor(Type.EmptyTypes)?.Invoke(new object[] { });
var plugin = (IPartition)type.GetConstructor(Type.EmptyTypes)?.Invoke(new object[]
{});
RegisterPartPlugin(plugin);
}
catch(Exception exception) { Console.WriteLine("Exception {0}", exception); }
catch(Exception exception)
{
Console.WriteLine("Exception {0}", exception);
}
assembly = Assembly.GetAssembly(typeof(IFilesystem));
foreach(Type type in assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IFilesystem)))
.Where(t => t.IsClass))
foreach(Type type in assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IFilesystem))).
Where(t => t.IsClass))
try
{
IFilesystem plugin = (IFilesystem)type.GetConstructor(Type.EmptyTypes)?.Invoke(new object[] { });
var plugin = (IFilesystem)type.GetConstructor(Type.EmptyTypes)?.Invoke(new object[]
{});
RegisterPlugin(plugin);
}
catch(Exception exception) { Console.WriteLine("Exception {0}", exception); }
catch(Exception exception)
{
Console.WriteLine("Exception {0}", exception);
}
assembly = Assembly.GetAssembly(typeof(IReadOnlyFilesystem));
foreach(Type type in assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IReadOnlyFilesystem)))
.Where(t => t.IsClass))
foreach(Type type in assembly.GetTypes().
Where(t => t.GetInterfaces().Contains(typeof(IReadOnlyFilesystem))).
Where(t => t.IsClass))
try
{
IReadOnlyFilesystem plugin =
(IReadOnlyFilesystem)type.GetConstructor(Type.EmptyTypes)?.Invoke(new object[] { });
var plugin = (IReadOnlyFilesystem)type.GetConstructor(Type.EmptyTypes)?.Invoke(new object[]
{});
RegisterReadOnlyFilesystem(plugin);
}
catch(Exception exception) { Console.WriteLine("Exception {0}", exception); }
catch(Exception exception)
{
Console.WriteLine("Exception {0}", exception);
}
assembly = Assembly.GetAssembly(typeof(IWritableImage));
foreach(Type type in assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IWritableImage)))
.Where(t => t.IsClass))
foreach(Type type in assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IWritableImage))).
Where(t => t.IsClass))
try
{
IWritableImage plugin =
(IWritableImage)type.GetConstructor(Type.EmptyTypes)?.Invoke(new object[] { });
var plugin = (IWritableImage)type.GetConstructor(Type.EmptyTypes)?.Invoke(new object[]
{});
RegisterWritableMedia(plugin);
}
catch(Exception exception) { Console.WriteLine("Exception {0}", exception); }
catch(Exception exception)
{
Console.WriteLine("Exception {0}", exception);
}
}
void RegisterImagePlugin(IMediaImage plugin)
@@ -143,7 +153,8 @@ namespace apprepodbmgr.Core
void RegisterPlugin(IFilesystem plugin)
{
if(!PluginsList.ContainsKey(plugin.Name.ToLower())) PluginsList.Add(plugin.Name.ToLower(), plugin);
if(!PluginsList.ContainsKey(plugin.Name.ToLower()))
PluginsList.Add(plugin.Name.ToLower(), plugin);
}
void RegisterReadOnlyFilesystem(IReadOnlyFilesystem plugin)
@@ -154,7 +165,8 @@ namespace apprepodbmgr.Core
void RegisterWritableMedia(IWritableImage plugin)
{
if(!WritableImages.ContainsKey(plugin.Name.ToLower())) WritableImages.Add(plugin.Name.ToLower(), plugin);
if(!WritableImages.ContainsKey(plugin.Name.ToLower()))
WritableImages.Add(plugin.Name.ToLower(), plugin);
}
void RegisterPartPlugin(IPartition partplugin)

View File

@@ -42,23 +42,30 @@ namespace apprepodbmgr.Core
try
{
string dataSrc = $"URI=file:{database}";
dbCon = new SQLiteConnection(dataSrc);
dbCon = new SQLiteConnection(dataSrc);
dbCon.Open();
const string SQL = "SELECT * FROM apprepodbmgr";
SQLiteCommand dbcmd = dbCon.CreateCommand();
dbcmd.CommandText = SQL;
SQLiteDataAdapter dAdapter = new SQLiteDataAdapter {SelectCommand = dbcmd};
DataSet dSet = new DataSet();
SQLiteCommand dbcmd = dbCon.CreateCommand();
dbcmd.CommandText = SQL;
var dAdapter = new SQLiteDataAdapter
{
SelectCommand = dbcmd
};
var dSet = new DataSet();
dAdapter.Fill(dSet);
DataTable dTable = dSet.Tables[0];
if(dTable.Rows.Count != 1) return false;
if(dTable.Rows.Count != 1)
return false;
if((long)dTable.Rows[0]["version"] != 1)
{
dbCon = null;
return false;
}
@@ -71,6 +78,7 @@ namespace apprepodbmgr.Core
Console.WriteLine("Error opening DB.");
Console.WriteLine(ex.Message);
dbCon = null;
return false;
}
}
@@ -87,37 +95,37 @@ namespace apprepodbmgr.Core
try
{
string dataSrc = $"URI=file:{database}";
dbCon = new SQLiteConnection(dataSrc);
dbCon = new SQLiteConnection(dataSrc);
dbCon.Open();
SQLiteCommand dbCmd = dbCon.CreateCommand();
#if DEBUG
#if DEBUG
Console.WriteLine("Creating apprepodbmgr table");
#endif
#endif
string sql = "CREATE TABLE apprepodbmgr ( version INTEGER, name TEXT )";
string sql = "CREATE TABLE apprepodbmgr ( version INTEGER, name TEXT )";
dbCmd.CommandText = sql;
dbCmd.ExecuteNonQuery();
sql =
"INSERT INTO apprepodbmgr ( version, name ) VALUES ( '1', 'Canary Islands Computer Museum' )";
sql = "INSERT INTO apprepodbmgr ( version, name ) VALUES ( '1', 'Canary Islands Computer Museum' )";
dbCmd.CommandText = sql;
dbCmd.ExecuteNonQuery();
#if DEBUG
#if DEBUG
Console.WriteLine("Creating applications table");
#endif
#endif
dbCmd.CommandText = Schema.AppsTableSql;
dbCmd.ExecuteNonQuery();
#if DEBUG
#if DEBUG
Console.WriteLine("Creating files table");
#endif
#endif
dbCmd.CommandText = Schema.FilesTableSql;
dbCmd.ExecuteNonQuery();
dbCmd.Dispose();
dbCon = null;
return true;
}
catch(SQLiteException ex)
@@ -125,14 +133,12 @@ namespace apprepodbmgr.Core
Console.WriteLine("Error opening DB.");
Console.WriteLine(ex.Message);
dbCon = null;
return false;
}
}
public override IDbDataAdapter GetNewDataAdapter()
{
return new SQLiteDataAdapter();
}
public override IDbDataAdapter GetNewDataAdapter() => new SQLiteDataAdapter();
public override long LastInsertRowId => dbCon.LastInsertRowId;
#endregion

View File

@@ -30,57 +30,46 @@ namespace apprepodbmgr.Core
{
public static class Schema
{
public const string FilesTableSql = "-- -----------------------------------------------------\n" +
"-- Table `files`\n" +
"-- -----------------------------------------------------\n" +
"DROP TABLE IF EXISTS `files` ;\n\n" +
"CREATE TABLE IF NOT EXISTS `files` (\n" +
" `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" `sha256` VARCHAR(64) NOT NULL,\n" +
" `crack` BOOLEAN NOT NULL,\n" +
" `hasvirus` BOOLEAN NULL,\n" +
" `clamtime` DATETIME NULL,\n" +
" `vtotaltime` DATETIME NULL,\n" +
" `virus` VARCHAR(128) NULL,\n" +
" `length` BIGINT NOT NULL);\n\n" +
"CREATE UNIQUE INDEX `files_id_UNIQUE` ON `files` (`id` ASC);\n\n" +
public const string FilesTableSql = "-- -----------------------------------------------------\n" +
"-- Table `files`\n" +
"-- -----------------------------------------------------\n" +
"DROP TABLE IF EXISTS `files` ;\n\n" +
"CREATE TABLE IF NOT EXISTS `files` (\n" +
" `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" `sha256` VARCHAR(64) NOT NULL,\n" + " `crack` BOOLEAN NOT NULL,\n" +
" `hasvirus` BOOLEAN NULL,\n" + " `clamtime` DATETIME NULL,\n" +
" `vtotaltime` DATETIME NULL,\n" + " `virus` VARCHAR(128) NULL,\n" +
" `length` BIGINT NOT NULL);\n\n" +
"CREATE UNIQUE INDEX `files_id_UNIQUE` ON `files` (`id` ASC);\n\n" +
"CREATE UNIQUE INDEX `files_sha256_UNIQUE` ON `files` (`sha256` ASC);\n\n" +
"CREATE INDEX `files_hasvirus_idx` ON `files` (`hasvirus` ASC);\n\n" +
"CREATE INDEX `files_virus_idx` ON `files` (`virus` ASC);\n\n" +
"CREATE INDEX `files_hasvirus_idx` ON `files` (`hasvirus` ASC);\n\n" +
"CREATE INDEX `files_virus_idx` ON `files` (`virus` ASC);\n\n" +
"CREATE INDEX `files_length_idx` ON `files` (`length` ASC);";
public const string AppsTableSql = "-- -----------------------------------------------------\n" +
"-- Table `apps`\n" +
"-- -----------------------------------------------------\n" +
"DROP TABLE IF EXISTS `apps` ;\n\n" +
"CREATE TABLE IF NOT EXISTS `apps` (\n" +
" `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" `mdid` CHAR(40) NOT NULL,\n" +
" `developer` VARCHAR(45) NOT NULL,\n" +
" `product` VARCHAR(45) NOT NULL,\n" +
" `version` VARCHAR(45) NULL,\n" +
" `languages` VARCHAR(45) NULL,\n" +
" `architecture` VARCHAR(45) NULL,\n" +
" `targetos` VARCHAR(45) NULL,\n" +
" `format` VARCHAR(45) NULL,\n" +
" `description` TEXT NULL,\n" +
" `oem` BOOLEAN NOT NULL,\n" +
" `upgrade` BOOLEAN NOT NULL,\n" +
" `update` BOOLEAN NOT NULL,\n" +
" `source` BOOLEAN NOT NULL,\n" +
" `files` BOOLEAN NOT NULL,\n" +
" `installer` BOOLEAN NOT NULL,\n" +
" `xml` BLOB NULL,\n" +
" `json` BLOB NULL,\n" +
" `icon` BLOB NULL);\n\n" +
"CREATE UNIQUE INDEX `apps_id_UNIQUE` ON `apps` (`id` ASC);\n\n" +
"CREATE UNIQUE INDEX `apps_mdid_UNIQUE` ON `apps` (`mdid` ASC);\n\n" +
"CREATE INDEX `apps_developer_idx` ON `apps` (`developer` ASC);\n\n" +
"CREATE INDEX `apps_product_idx` ON `apps` (`product` ASC);\n\n" +
"CREATE INDEX `apps_version_idx` ON `apps` (`version` ASC);\n\n" +
public const string AppsTableSql = "-- -----------------------------------------------------\n" +
"-- Table `apps`\n" +
"-- -----------------------------------------------------\n" +
"DROP TABLE IF EXISTS `apps` ;\n\n" +
"CREATE TABLE IF NOT EXISTS `apps` (\n" +
" `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" `mdid` CHAR(40) NOT NULL,\n" + " `developer` VARCHAR(45) NOT NULL,\n" +
" `product` VARCHAR(45) NOT NULL,\n" + " `version` VARCHAR(45) NULL,\n" +
" `languages` VARCHAR(45) NULL,\n" +
" `architecture` VARCHAR(45) NULL,\n" + " `targetos` VARCHAR(45) NULL,\n" +
" `format` VARCHAR(45) NULL,\n" + " `description` TEXT NULL,\n" +
" `oem` BOOLEAN NOT NULL,\n" + " `upgrade` BOOLEAN NOT NULL,\n" +
" `update` BOOLEAN NOT NULL,\n" + " `source` BOOLEAN NOT NULL,\n" +
" `files` BOOLEAN NOT NULL,\n" + " `installer` BOOLEAN NOT NULL,\n" +
" `xml` BLOB NULL,\n" + " `json` BLOB NULL,\n" +
" `icon` BLOB NULL);\n\n" +
"CREATE UNIQUE INDEX `apps_id_UNIQUE` ON `apps` (`id` ASC);\n\n" +
"CREATE UNIQUE INDEX `apps_mdid_UNIQUE` ON `apps` (`mdid` ASC);\n\n" +
"CREATE INDEX `apps_developer_idx` ON `apps` (`developer` ASC);\n\n" +
"CREATE INDEX `apps_product_idx` ON `apps` (`product` ASC);\n\n" +
"CREATE INDEX `apps_version_idx` ON `apps` (`version` ASC);\n\n" +
"CREATE INDEX `apps_architecture_idx` ON `apps` (`architecture` ASC);\n\n" +
"CREATE INDEX `apps_format_idx` ON `apps` (`format` ASC);\n\n" +
"CREATE INDEX `apps_targetos_idx` ON `apps` (`targetos` ASC);\n\n" +
"CREATE INDEX `apps_format_idx` ON `apps` (`format` ASC);\n\n" +
"CREATE INDEX `apps_targetos_idx` ON `apps` (`targetos` ASC);\n\n" +
"CREATE INDEX `apps_description_idx` ON `apps` (`description` ASC);";
}
}

View File

@@ -59,7 +59,7 @@ namespace apprepodbmgr.Core
public static void LoadSettings()
{
Current = new SetSettings();
Current = new SetSettings();
PlatformID ptId = DetectOS.GetRealPlatformID();
FileStream prefsFs = null;
@@ -75,6 +75,7 @@ namespace apprepodbmgr.Core
string preferencesPath =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library",
"Preferences");
string preferencesFilePath =
Path.Combine(preferencesPath, "com.claunia.museum.apprepodbmgr.plist");
@@ -84,36 +85,36 @@ namespace apprepodbmgr.Core
SaveSettings();
}
prefsFs = new FileStream(preferencesFilePath, FileMode.Open);
NSDictionary parsedPreferences = (NSDictionary)BinaryPropertyListParser.Parse(prefsFs);
prefsFs = new FileStream(preferencesFilePath, FileMode.Open);
var parsedPreferences = (NSDictionary)BinaryPropertyListParser.Parse(prefsFs);
if(parsedPreferences != null)
{
Current.TemporaryFolder = parsedPreferences.TryGetValue("TemporaryFolder", out NSObject obj)
? ((NSString)obj).ToString()
: Path.GetTempPath();
? ((NSString)obj).ToString() : Path.GetTempPath();
Current.DatabasePath = parsedPreferences.TryGetValue("DatabasePath", out obj)
? ((NSString)obj).ToString()
: Path
.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
: Path.
Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"apprepodbmgr.db");
Current.RepositoryPath = parsedPreferences.TryGetValue("RepositoryPath", out obj)
? ((NSString)obj).ToString()
: Path
.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
: Path.
Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"apprepo");
Current.UnArchiverPath = parsedPreferences.TryGetValue("UnArchiverPath", out obj)
? ((NSString)obj).ToString()
: null;
? ((NSString)obj).ToString() : null;
if(parsedPreferences.TryGetValue("CompressionAlgorithm", out obj))
{
if(!Enum.TryParse(((NSString)obj).ToString(), true, out Current.CompressionAlgorithm))
Current.CompressionAlgorithm = AlgoEnum.GZip;
}
else Current.CompressionAlgorithm = AlgoEnum.GZip;
else
Current.CompressionAlgorithm = AlgoEnum.GZip;
Current.UseAntivirus = parsedPreferences.TryGetValue("UseAntivirus", out obj) &&
((NSNumber)obj).ToBool();
@@ -122,12 +123,12 @@ namespace apprepodbmgr.Core
((NSNumber)obj).ToBool();
Current.ClamdHost = parsedPreferences.TryGetValue("ClamdHost", out obj)
? ((NSString)obj).ToString()
: null;
? ((NSString)obj).ToString() : null;
if(parsedPreferences.TryGetValue("ClamdPort", out obj))
Current.ClamdPort = (ushort)((NSNumber)obj).ToLong();
else Current.ClamdPort = 3310;
Current.ClamdPort = (ushort)((NSNumber)obj).ToLong();
else
Current.ClamdPort = 3310;
Current.ClamdIsLocal = parsedPreferences.TryGetValue("ClamdIsLocal", out obj) &&
((NSNumber)obj).ToBool();
@@ -136,8 +137,7 @@ namespace apprepodbmgr.Core
((NSNumber)obj).ToBool();
Current.ClamdHost = parsedPreferences.TryGetValue("VirusTotalKey", out obj)
? ((NSString)obj).ToString()
: null;
? ((NSString)obj).ToString() : null;
prefsFs.Close();
}
@@ -149,6 +149,7 @@ namespace apprepodbmgr.Core
SaveSettings();
}
}
break;
case PlatformID.Win32NT:
case PlatformID.Win32S:
@@ -156,21 +157,24 @@ namespace apprepodbmgr.Core
case PlatformID.WinCE:
case PlatformID.WindowsPhone:
{
RegistryKey parentKey = Registry
.CurrentUser.OpenSubKey("SOFTWARE")
?.OpenSubKey("Canary Islands Computer Museum");
RegistryKey parentKey = Registry.CurrentUser.OpenSubKey("SOFTWARE")?.
OpenSubKey("Canary Islands Computer Museum");
if(parentKey == null)
{
SetDefaultSettings();
SaveSettings();
return;
}
RegistryKey key = parentKey.OpenSubKey("AppRepoDBMgr");
if(key == null)
{
SetDefaultSettings();
SaveSettings();
return;
}
@@ -178,37 +182,42 @@ namespace apprepodbmgr.Core
Current.DatabasePath = (string)key.GetValue("DatabasePath");
Current.RepositoryPath = (string)key.GetValue("RepositoryPath");
Current.UnArchiverPath = (string)key.GetValue("UnArchiverPath");
if(!Enum.TryParse((string)key.GetValue("CompressionAlgorithm"), true,
out Current.CompressionAlgorithm))
Current.CompressionAlgorithm = AlgoEnum.GZip;
Current.UseAntivirus = bool.Parse((string)key.GetValue("UseAntivirus"));
Current.UseClamd = bool.Parse((string)key.GetValue("UseClamd"));
Current.ClamdHost = (string)key.GetValue("ClamdHost");
Current.ClamdPort = ushort.Parse((string)key.GetValue("ClamdPort"));
Current.ClamdIsLocal = bool.Parse((string)key.GetValue("ClamdIsLocal"));
Current.UseAntivirus = bool.Parse((string)key.GetValue("UseAntivirus"));
Current.UseClamd = bool.Parse((string)key.GetValue("UseClamd"));
Current.ClamdHost = (string)key.GetValue("ClamdHost");
Current.ClamdPort = ushort.Parse((string)key.GetValue("ClamdPort"));
Current.ClamdIsLocal = bool.Parse((string)key.GetValue("ClamdIsLocal"));
Current.UseVirusTotal = bool.Parse((string)key.GetValue("UseVirusTotal"));
Current.VirusTotalKey = (string)key.GetValue("VirusTotalKey");
Current.VirusTotalKey = (string)key.GetValue("VirusTotalKey");
}
break;
default:
{
string configPath =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config");
string settingsPath =
Path.Combine(configPath, "AppRepoDBMgr.xml");
string settingsPath = Path.Combine(configPath, "AppRepoDBMgr.xml");
if(!Directory.Exists(configPath))
{
SetDefaultSettings();
SaveSettings();
return;
}
XmlSerializer xs = new XmlSerializer(Current.GetType());
prefsSr = new StreamReader(settingsPath);
Current = (SetSettings)xs.Deserialize(prefsSr);
var xs = new XmlSerializer(Current.GetType());
prefsSr = new StreamReader(settingsPath);
Current = (SetSettings)xs.Deserialize(prefsSr);
prefsSr.Close();
}
break;
}
}
@@ -233,32 +242,58 @@ namespace apprepodbmgr.Core
case PlatformID.MacOSX:
case PlatformID.iOS:
{
NSDictionary root = new NSDictionary
var root = new NSDictionary
{
{"TemporaryFolder", Current.TemporaryFolder},
{"DatabasePath", Current.DatabasePath},
{"RepositoryPath", Current.RepositoryPath},
{"UnArchiverPath", Current.UnArchiverPath},
{"CompressionAlgorithm", Current.CompressionAlgorithm.ToString()},
{"UseAntivirus", Current.UseAntivirus},
{"UseClamd", Current.UseClamd},
{"ClamdHost", Current.ClamdHost},
{"ClamdPort", Current.ClamdPort},
{"ClamdIsLocal", Current.ClamdIsLocal},
{"UseVirusTotal", Current.UseVirusTotal},
{"VirusTotalKey", Current.VirusTotalKey}
{
"TemporaryFolder", Current.TemporaryFolder
},
{
"DatabasePath", Current.DatabasePath
},
{
"RepositoryPath", Current.RepositoryPath
},
{
"UnArchiverPath", Current.UnArchiverPath
},
{
"CompressionAlgorithm", Current.CompressionAlgorithm.ToString()
},
{
"UseAntivirus", Current.UseAntivirus
},
{
"UseClamd", Current.UseClamd
},
{
"ClamdHost", Current.ClamdHost
},
{
"ClamdPort", Current.ClamdPort
},
{
"ClamdIsLocal", Current.ClamdIsLocal
},
{
"UseVirusTotal", Current.UseVirusTotal
},
{
"VirusTotalKey", Current.VirusTotalKey
}
};
string preferencesPath =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library",
"Preferences");
string preferencesFilePath =
Path.Combine(preferencesPath, "com.claunia.museum.apprepodbmgr.plist");
FileStream fs = new FileStream(preferencesFilePath, FileMode.Create);
var fs = new FileStream(preferencesFilePath, FileMode.Create);
BinaryPropertyListWriter.Write(fs, root);
fs.Close();
}
break;
case PlatformID.Win32NT:
case PlatformID.Win32S:
@@ -266,43 +301,48 @@ namespace apprepodbmgr.Core
case PlatformID.WinCE:
case PlatformID.WindowsPhone:
{
RegistryKey parentKey = Registry
.CurrentUser.OpenSubKey("SOFTWARE", true)
?.CreateSubKey("Canary Islands Computer Museum");
RegistryKey parentKey = Registry.CurrentUser.OpenSubKey("SOFTWARE", true)?.
CreateSubKey("Canary Islands Computer Museum");
RegistryKey key = parentKey?.CreateSubKey("AppRepoDBMgr");
if(key != null)
{
key.SetValue("TemporaryFolder", Current.TemporaryFolder);
key.SetValue("DatabasePath", Current.DatabasePath);
key.SetValue("RepositoryPath", Current.RepositoryPath);
if(Current.UnArchiverPath != null) key.SetValue("UnArchiverPath", Current.UnArchiverPath);
key.SetValue("CompressionAlgorithm",
Current.CompressionAlgorithm);
key.SetValue("UseAntivirus", Current.UseAntivirus);
key.SetValue("UseClamd", Current.UseClamd);
key.SetValue("ClamdHost", Current.ClamdHost == null ? "" : Current.ClamdHost);
key.SetValue("ClamdPort", Current.ClamdPort);
key.SetValue("ClamdIsLocal", Current.ClamdIsLocal);
key.SetValue("TemporaryFolder", Current.TemporaryFolder);
key.SetValue("DatabasePath", Current.DatabasePath);
key.SetValue("RepositoryPath", Current.RepositoryPath);
if(Current.UnArchiverPath != null)
key.SetValue("UnArchiverPath", Current.UnArchiverPath);
key.SetValue("CompressionAlgorithm", Current.CompressionAlgorithm);
key.SetValue("UseAntivirus", Current.UseAntivirus);
key.SetValue("UseClamd", Current.UseClamd);
key.SetValue("ClamdHost", Current.ClamdHost == null ? "" : Current.ClamdHost);
key.SetValue("ClamdPort", Current.ClamdPort);
key.SetValue("ClamdIsLocal", Current.ClamdIsLocal);
key.SetValue("UseVirusTotal", Current.UseVirusTotal);
key.SetValue("VirusTotalKey", Current.VirusTotalKey == null ? "" : Current.VirusTotalKey);
}
}
break;
default:
{
string configPath =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config");
string settingsPath =
Path.Combine(configPath, "AppRepoDBMgr.xml");
if(!Directory.Exists(configPath)) Directory.CreateDirectory(configPath);
string settingsPath = Path.Combine(configPath, "AppRepoDBMgr.xml");
FileStream fs = new FileStream(settingsPath, FileMode.Create);
XmlSerializer xs = new XmlSerializer(Current.GetType());
if(!Directory.Exists(configPath))
Directory.CreateDirectory(configPath);
var fs = new FileStream(settingsPath, FileMode.Create);
var xs = new XmlSerializer(Current.GetType());
xs.Serialize(fs, Current);
fs.Close();
}
break;
}
}
@@ -310,29 +350,26 @@ namespace apprepodbmgr.Core
catch
#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body
{
if(Debugger.IsAttached) throw;
if(Debugger.IsAttached)
throw;
}
}
static void SetDefaultSettings()
static void SetDefaultSettings() => Current = new SetSettings
{
Current = new SetSettings
{
TemporaryFolder = Path.GetTempPath(),
DatabasePath =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "apprepodbmgr.db"),
RepositoryPath =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "apprepo"),
UnArchiverPath = null,
CompressionAlgorithm = AlgoEnum.GZip,
UseAntivirus = false,
UseClamd = false,
ClamdHost = null,
ClamdPort = 3310,
ClamdIsLocal = false,
UseVirusTotal = false,
VirusTotalKey = null
};
}
TemporaryFolder = Path.GetTempPath(),
DatabasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"apprepodbmgr.db"),
RepositoryPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "apprepo"),
UnArchiverPath = null,
CompressionAlgorithm = AlgoEnum.GZip,
UseAntivirus = false,
UseClamd = false,
ClamdHost = null,
ClamdPort = 3310,
ClamdIsLocal = false,
UseVirusTotal = false,
VirusTotalKey = null
};
}
}

View File

@@ -15,7 +15,8 @@ namespace apprepodbmgr.Core
int ret = readlink(path, buf, 16384);
if(ret < 0) return null;
if(ret < 0)
return null;
byte[] target = new byte[ret];
Marshal.Copy(buf, target, 0, ret);
@@ -26,9 +27,6 @@ namespace apprepodbmgr.Core
[DllImport("libc", CharSet = CharSet.Ansi, SetLastError = true)]
static extern int symlink(string target, string path);
public static int Symlink(string target, string path)
{
return symlink(target, path);
}
public static int Symlink(string target, string path) => symlink(target, path);
}
}

View File

@@ -46,27 +46,26 @@ namespace apprepodbmgr.Core
public static void InitClamd()
{
if(!Settings.Current.UseClamd || !Settings.Current.UseAntivirus)
if(!Settings.Current.UseClamd ||
!Settings.Current.UseAntivirus)
{
Context.ClamdVersion = null;
return;
}
TestClamd();
}
public static void TestClamd()
public static void TestClamd() => Task.Run(async () =>
{
Task.Run(async () =>
try
{
try
{
clam = new ClamClient(Settings.Current.ClamdHost, Settings.Current.ClamdPort);
Context.ClamdVersion = await clam.GetVersionAsync();
}
catch(SocketException) { }
}).Wait();
}
clam = new ClamClient(Settings.Current.ClamdHost, Settings.Current.ClamdPort);
Context.ClamdVersion = await clam.GetVersionAsync();
}
catch(SocketException) {}
}).Wait();
public static void ClamScanFileFromRepo(DbFile file)
{
@@ -75,10 +74,12 @@ namespace apprepodbmgr.Core
if(Context.ClamdVersion == null)
{
Failed?.Invoke("clamd is not usable");
return;
}
if(clam == null) Failed?.Invoke("clamd is not initalized");
if(clam == null)
Failed?.Invoke("clamd is not initalized");
string repoPath;
AlgoEnum algorithm;
@@ -90,6 +91,7 @@ namespace apprepodbmgr.Core
repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
file.Sha256[1].ToString(), file.Sha256[2].ToString(),
file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".gz");
algorithm = AlgoEnum.GZip;
}
else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
@@ -100,6 +102,7 @@ namespace apprepodbmgr.Core
repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
file.Sha256[1].ToString(), file.Sha256[2].ToString(),
file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".bz2");
algorithm = AlgoEnum.BZip2;
}
else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
@@ -111,6 +114,7 @@ namespace apprepodbmgr.Core
file.Sha256[1].ToString(), file.Sha256[2].ToString(),
file.Sha256[3].ToString(), file.Sha256[4].ToString(),
file.Sha256 + ".lzma");
algorithm = AlgoEnum.LZMA;
}
else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
@@ -121,11 +125,13 @@ namespace apprepodbmgr.Core
repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
file.Sha256[1].ToString(), file.Sha256[2].ToString(),
file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".lz");
algorithm = AlgoEnum.LZip;
}
else
{
Failed?.Invoke($"Cannot find file with hash {file.Sha256} in the repository");
return;
}
@@ -133,11 +139,12 @@ namespace apprepodbmgr.Core
Stream zStream = null;
if(Settings.Current.ClamdIsLocal)
if(algorithm == AlgoEnum.LZMA || algorithm == AlgoEnum.LZip)
if(algorithm == AlgoEnum.LZMA ||
algorithm == AlgoEnum.LZip)
{
string tmpFile = Path.Combine(Settings.Current.TemporaryFolder, Path.GetTempFileName());
FileStream outFs = new FileStream(tmpFile, FileMode.Create, FileAccess.Write);
FileStream inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read);
string tmpFile = Path.Combine(Settings.Current.TemporaryFolder, Path.GetTempFileName());
var outFs = new FileStream(tmpFile, FileMode.Create, FileAccess.Write);
var inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read);
if(algorithm == AlgoEnum.LZMA)
{
@@ -146,34 +153,39 @@ namespace apprepodbmgr.Core
inFs.Seek(8, SeekOrigin.Current);
zStream = new LzmaStream(properties, inFs, inFs.Length - 13, file.Length);
}
else zStream = new LZipStream(inFs, CompressionMode.Decompress);
else
zStream = new LZipStream(inFs, CompressionMode.Decompress);
UpdateProgress?.Invoke("Uncompressing file...", null, 0, 0);
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
#endif
zStream.CopyTo(outFs);
zStream.Close();
outFs.Close();
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.ClamScanFileFromRepo({0}): Uncompressing took {1} seconds", file,
stopwatch.Elapsed.TotalSeconds);
#endif
#endif
UpdateProgress?.Invoke("Requesting local scan to clamd server...", null, 0, 0);
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
Task.Run(async () => { result = await clam.ScanFileOnServerMultithreadedAsync(tmpFile); })
.Wait();
#if DEBUG
#endif
Task.Run(async () =>
{
result = await clam.ScanFileOnServerMultithreadedAsync(tmpFile);
}).Wait();
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.ClamScanFileFromRepo({0}): Clamd took {1} seconds to scan", file,
stopwatch.Elapsed.TotalSeconds);
#endif
#endif
File.Delete(tmpFile);
}
@@ -181,55 +193,67 @@ namespace apprepodbmgr.Core
{
UpdateProgress?.Invoke("Requesting local scan to clamd server...", null, 0, 0);
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
Task.Run(async () => { result = await clam.ScanFileOnServerMultithreadedAsync(repoPath); })
.Wait();
#if DEBUG
#endif
Task.Run(async () =>
{
result = await clam.ScanFileOnServerMultithreadedAsync(repoPath);
}).Wait();
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.ClamScanFileFromRepo({0}): Clamd took {1} seconds to scan", file,
stopwatch.Elapsed.TotalSeconds);
#endif
#endif
}
else
{
FileStream inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read);
var inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read);
switch(algorithm)
{
case AlgoEnum.GZip:
zStream = new GZipStream(inFs, CompressionMode.Decompress);
break;
case AlgoEnum.BZip2:
zStream = new BZip2Stream(inFs, CompressionMode.Decompress);
break;
case AlgoEnum.LZMA:
byte[] properties = new byte[5];
inFs.Read(properties, 0, 5);
inFs.Seek(8, SeekOrigin.Current);
zStream = new LzmaStream(properties, inFs, inFs.Length - 13, file.Length);
break;
case AlgoEnum.LZip:
zStream = new LZipStream(inFs, CompressionMode.Decompress);
break;
}
UpdateProgress?.Invoke("Uploading file to clamd server...", null, 0, 0);
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
Task.Run(async () => { result = await clam.SendAndScanFileAsync(zStream); }).Wait();
#if DEBUG
#endif
Task.Run(async () =>
{
result = await clam.SendAndScanFileAsync(zStream);
}).Wait();
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.ClamScanFileFromRepo({0}): Clamd took {1} seconds to scan", file,
stopwatch.Elapsed.TotalSeconds);
#endif
#endif
zStream.Close();
}
if(result.InfectedFiles != null && result.InfectedFiles.Count > 0)
if(result.InfectedFiles != null &&
result.InfectedFiles.Count > 0)
{
file.HasVirus = true;
file.Virus = result.InfectedFiles[0].VirusName;
@@ -248,13 +272,13 @@ namespace apprepodbmgr.Core
ScanFinished?.Invoke(file);
}
catch(ThreadAbortException) { }
catch(ThreadAbortException) {}
catch(Exception ex)
{
Failed?.Invoke($"Exception {ex.Message} when calling clamd");
#if DEBUG
#if DEBUG
Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException);
#endif
#endif
}
}
@@ -262,19 +286,22 @@ namespace apprepodbmgr.Core
{
UpdateProgress2?.Invoke("Asking database for files", null, 0, 0);
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
#endif
if(!dbCore.DbOps.GetNotAvFiles(out List<DbFile> files))
Failed?.Invoke("Could not get files from database.");
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.ClamScanAllFiles(): Took {0} seconds to get files from database",
stopwatch.Elapsed.TotalSeconds);
stopwatch.Restart();
#endif
#endif
int counter = 0;
foreach(DbFile file in files)
{
UpdateProgress2?.Invoke($"Scanning file {counter} of {files.Count}", null, counter, files.Count);
@@ -283,11 +310,12 @@ namespace apprepodbmgr.Core
counter++;
}
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.ClamScanAllFiles(): Took {0} seconds scan all pending files",
stopwatch.Elapsed.TotalSeconds);
#endif
#endif
Finished?.Invoke();
}

View File

@@ -53,18 +53,21 @@ namespace apprepodbmgr.Core
if(string.IsNullOrWhiteSpace(Context.DbInfo.Developer))
{
Failed?.Invoke("Developer cannot be empty");
return;
}
if(string.IsNullOrWhiteSpace(Context.DbInfo.Product))
{
Failed?.Invoke("Product cannot be empty");
return;
}
if(string.IsNullOrWhiteSpace(Context.DbInfo.Version))
{
Failed?.Invoke("Version cannot be empty");
return;
}
@@ -72,53 +75,73 @@ namespace apprepodbmgr.Core
destinationFolder += Path.DirectorySeparatorChar + Context.DbInfo.Developer;
destinationFolder += Path.DirectorySeparatorChar + Context.DbInfo.Product;
destinationFolder += Path.DirectorySeparatorChar + Context.DbInfo.Version;
if(!string.IsNullOrWhiteSpace(Context.DbInfo.Languages))
destinationFolder += Path.DirectorySeparatorChar + Context.DbInfo.Languages;
if(!string.IsNullOrWhiteSpace(Context.DbInfo.Architecture))
destinationFolder += Path.DirectorySeparatorChar + Context.DbInfo.Architecture;
if(Context.DbInfo.Oem) destinationFolder += Path.DirectorySeparatorChar + "oem";
if(Context.DbInfo.Oem)
destinationFolder += Path.DirectorySeparatorChar + "oem";
if(!string.IsNullOrWhiteSpace(Context.DbInfo.TargetOs))
destinationFolder += Path.DirectorySeparatorChar + "for " + Context.DbInfo.TargetOs;
string destinationFile = "";
if(!string.IsNullOrWhiteSpace(Context.DbInfo.Format))
destinationFile += "[" + Context.DbInfo.Format + "]";
if(Context.DbInfo.Files)
{
if(destinationFile != "") destinationFile += "_";
if(destinationFile != "")
destinationFile += "_";
destinationFile += "files";
}
if(Context.DbInfo.Installer)
{
if(destinationFile != "") destinationFile += "_";
if(destinationFile != "")
destinationFile += "_";
destinationFile += "installer";
}
if(Context.DbInfo.Source)
{
if(destinationFile != "") destinationFile += "_";
if(destinationFile != "")
destinationFile += "_";
destinationFile += "source";
}
if(Context.DbInfo.Update)
{
if(destinationFile != "") destinationFile += "_";
if(destinationFile != "")
destinationFile += "_";
destinationFile += "update";
}
if(Context.DbInfo.Upgrade)
{
if(destinationFile != "") destinationFile += "_";
if(destinationFile != "")
destinationFile += "_";
destinationFile += "upgrade";
}
if(!string.IsNullOrWhiteSpace(Context.DbInfo.Description))
{
if(destinationFile != "") destinationFile += "_";
if(destinationFile != "")
destinationFile += "_";
destinationFile += Context.DbInfo.Description;
}
else if(destinationFile == "") destinationFile = "archive";
else if(destinationFile == "")
destinationFile = "archive";
string destination = destinationFolder + Path.DirectorySeparatorChar + destinationFile + ".zip";
@@ -130,16 +153,19 @@ namespace apprepodbmgr.Core
if(File.Exists(destination))
{
Failed?.Invoke("Application already exists.");
return;
}
Failed?.Invoke("Application already exists in the database but not in the repository, check for inconsistencies.");
return;
}
if(File.Exists(destination))
{
Failed?.Invoke("Application already exists in the repository but not in the database, check for inconsistencies.");
return;
}
@@ -147,9 +173,11 @@ namespace apprepodbmgr.Core
string filesPath;
if(!string.IsNullOrEmpty(Context.TmpFolder) && Directory.Exists(Context.TmpFolder))
filesPath = Context.TmpFolder;
else filesPath = Context.Path;
if(!string.IsNullOrEmpty(Context.TmpFolder) &&
Directory.Exists(Context.TmpFolder))
filesPath = Context.TmpFolder;
else
filesPath = Context.Path;
string extension = null;
@@ -157,24 +185,30 @@ namespace apprepodbmgr.Core
{
case AlgoEnum.GZip:
extension = ".gz";
break;
case AlgoEnum.BZip2:
extension = ".bz2";
break;
case AlgoEnum.LZMA:
extension = ".lzma";
break;
case AlgoEnum.LZip:
extension = ".lz";
break;
}
long totalSize = 0, currentSize = 0;
foreach(KeyValuePair<string, DbAppFile> file in Context.Hashes) totalSize += file.Value.Length;
long totalSize = 0, currentSize = 0;
#if DEBUG
foreach(KeyValuePair<string, DbAppFile> file in Context.Hashes)
totalSize += file.Value.Length;
#if DEBUG
stopwatch.Restart();
#endif
#endif
foreach(KeyValuePair<string, DbAppFile> file in Context.Hashes)
{
UpdateProgress?.Invoke("Compressing...", file.Value.Path, currentSize, totalSize);
@@ -182,34 +216,42 @@ namespace apprepodbmgr.Core
destinationFolder = Path.Combine(Settings.Current.RepositoryPath, file.Value.Sha256[0].ToString(),
file.Value.Sha256[1].ToString(), file.Value.Sha256[2].ToString(),
file.Value.Sha256[3].ToString(), file.Value.Sha256[4].ToString());
Directory.CreateDirectory(destinationFolder);
destinationFile = Path.Combine(destinationFolder, file.Value.Sha256 + extension);
if(!File.Exists(destinationFile))
{
FileStream inFs = new FileStream(Path.Combine(filesPath, file.Value.Path), FileMode.Open,
FileAccess.Read);
FileStream outFs = new FileStream(destinationFile, FileMode.CreateNew, FileAccess.Write);
Stream zStream = null;
var inFs = new FileStream(Path.Combine(filesPath, file.Value.Path), FileMode.Open,
FileAccess.Read);
var outFs = new FileStream(destinationFile, FileMode.CreateNew, FileAccess.Write);
Stream zStream = null;
switch(Settings.Current.CompressionAlgorithm)
{
case AlgoEnum.GZip:
zStream = new GZipStream(outFs, CompressionMode.Compress,
CompressionLevel.BestCompression);
break;
case AlgoEnum.BZip2:
zStream = new BZip2Stream(outFs, CompressionMode.Compress);
break;
case AlgoEnum.LZMA:
zStream = new LzmaStream(new LzmaEncoderProperties(), false, outFs);
outFs.Write(((LzmaStream)zStream).Properties, 0,
((LzmaStream)zStream).Properties.Length);
outFs.Write(BitConverter.GetBytes(inFs.Length), 0, 8);
break;
case AlgoEnum.LZip:
zStream = new LZipStream(outFs, CompressionMode.Compress);
break;
}
@@ -220,6 +262,7 @@ namespace apprepodbmgr.Core
UpdateProgress2?.Invoke($"{inFs.Position / (double)inFs.Length:P}",
$"{inFs.Position} / {inFs.Length} bytes", inFs.Position,
inFs.Length);
UpdateProgress?.Invoke("Compressing...", file.Value.Path, currentSize, totalSize);
inFs.Read(buffer, 0, buffer.Length);
@@ -228,8 +271,10 @@ namespace apprepodbmgr.Core
}
buffer = new byte[inFs.Length - inFs.Position];
UpdateProgress2?.Invoke($"{inFs.Position / (double)inFs.Length:P}",
$"{inFs.Position} / {inFs.Length} bytes", inFs.Position, inFs.Length);
UpdateProgress?.Invoke("Compressing...", file.Value.Path, currentSize, totalSize);
inFs.Read(buffer, 0, buffer.Length);
@@ -243,28 +288,31 @@ namespace apprepodbmgr.Core
zStream.Close();
outFs.Dispose();
}
else currentSize += file.Value.Length;
else
currentSize += file.Value.Length;
}
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.CompressFiles(): Took {0} seconds to compress files",
stopwatch.Elapsed.TotalSeconds);
#endif
#endif
if(Context.Metadata != null)
{
MemoryStream xms = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(CICMMetadataType));
var xms = new MemoryStream();
var xs = new XmlSerializer(typeof(CICMMetadataType));
xs.Serialize(xms, Context.Metadata);
xms.Position = 0;
JsonSerializer js = new JsonSerializer
var js = new JsonSerializer
{
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore
};
MemoryStream jms = new MemoryStream();
StreamWriter sw = new StreamWriter(jms, Encoding.UTF8, 1048576, true);
var jms = new MemoryStream();
var sw = new StreamWriter(jms, Encoding.UTF8, 1048576, true);
js.Serialize(sw, Context.Metadata, typeof(CICMMetadataType));
sw.Close();
jms.Position = 0;
@@ -272,14 +320,18 @@ namespace apprepodbmgr.Core
destinationFolder = Path.Combine(Settings.Current.RepositoryPath, "metadata", mdid[0].ToString(),
mdid[1].ToString(), mdid[2].ToString(), mdid[3].ToString(),
mdid[4].ToString());
Directory.CreateDirectory(destinationFolder);
FileStream xfs = new FileStream(Path.Combine(destinationFolder, mdid + ".xml"), FileMode.CreateNew,
FileAccess.Write);
var xfs = new FileStream(Path.Combine(destinationFolder, mdid + ".xml"), FileMode.CreateNew,
FileAccess.Write);
xms.CopyTo(xfs);
xfs.Close();
FileStream jfs = new FileStream(Path.Combine(destinationFolder, mdid + ".json"), FileMode.CreateNew,
FileAccess.Write);
var jfs = new FileStream(Path.Combine(destinationFolder, mdid + ".json"), FileMode.CreateNew,
FileAccess.Write);
jms.CopyTo(jfs);
jfs.Close();
@@ -289,15 +341,16 @@ namespace apprepodbmgr.Core
FinishedWithText?.Invoke($"Correctly added application with MDID {mdid}");
}
catch(ThreadAbortException) { }
catch(ThreadAbortException) {}
catch(Exception ex)
{
if(Debugger.IsAttached) throw;
if(Debugger.IsAttached)
throw;
Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}");
#if DEBUG
#if DEBUG
Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException);
#endif
#endif
}
}
@@ -306,12 +359,14 @@ namespace apprepodbmgr.Core
if(!Context.UnarUsable)
{
Failed?.Invoke("The UnArchiver is not correctly installed");
return;
}
if(!File.Exists(Context.Path))
{
Failed?.Invoke("Specified file cannot be found");
return;
}
@@ -323,10 +378,10 @@ namespace apprepodbmgr.Core
string lsarfilename = unarfilename?.Replace("unar", "lsar");
string lsarPath = Path.Combine(unarFolder, lsarfilename + extension);
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
Process lsarProcess = new Process
#endif
var lsarProcess = new Process
{
StartInfo =
{
@@ -337,37 +392,46 @@ namespace apprepodbmgr.Core
Arguments = $"-j \"\"\"{Context.Path}\"\"\""
}
};
lsarProcess.Start();
string lsarOutput = lsarProcess.StandardOutput.ReadToEnd();
lsarProcess.WaitForExit();
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.OpenArchive(): Took {0} seconds to list archive contents",
stopwatch.Elapsed.TotalSeconds);
stopwatch.Restart();
#endif
long counter = 0;
string format = null;
JsonTextReader jsReader = new JsonTextReader(new StringReader(lsarOutput));
#endif
long counter = 0;
string format = null;
var jsReader = new JsonTextReader(new StringReader(lsarOutput));
while(jsReader.Read())
switch(jsReader.TokenType)
{
case JsonToken.PropertyName
when jsReader.Value != null && jsReader.Value.ToString() == "XADFileName":
counter++;
break;
case JsonToken.PropertyName
when jsReader.Value != null && jsReader.Value.ToString() == "lsarFormatName":
jsReader.Read();
if(jsReader.TokenType == JsonToken.String && jsReader.Value != null)
if(jsReader.TokenType == JsonToken.String &&
jsReader.Value != null)
format = jsReader.Value.ToString();
break;
}
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.OpenArchive(): Took {0} seconds to process archive contents",
stopwatch.Elapsed.TotalSeconds);
#endif
#endif
Context.UnzipWithUnAr = false;
Context.ArchiveFormat = format;
@@ -376,12 +440,14 @@ namespace apprepodbmgr.Core
if(string.IsNullOrEmpty(format))
{
Failed?.Invoke("File not recognized as an archive");
return;
}
if(counter == 0)
{
Failed?.Invoke("Archive contains no files");
return;
}
@@ -391,37 +457,46 @@ namespace apprepodbmgr.Core
if(Context.UsableDotNetZip)
{
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
ZipFile zf = ZipFile.Read(Context.Path, new ReadOptions {Encoding = Encoding.UTF8});
#endif
var zf = ZipFile.Read(Context.Path, new ReadOptions
{
Encoding = Encoding.UTF8
});
foreach(ZipEntry ze in zf)
{
// ZIP created with Mac OS X, need to be extracted with The UnArchiver to get correct ResourceFork structure
if(!ze.FileName.StartsWith("__MACOSX", StringComparison.CurrentCulture)) continue;
if(!ze.FileName.StartsWith("__MACOSX", StringComparison.CurrentCulture))
continue;
Context.UnzipWithUnAr = true;
break;
}
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.OpenArchive(): Took {0} seconds to navigate in search of Mac OS X metadata",
stopwatch.Elapsed.TotalSeconds);
#endif
Console.
WriteLine("Core.OpenArchive(): Took {0} seconds to navigate in search of Mac OS X metadata",
stopwatch.Elapsed.TotalSeconds);
#endif
}
}
Finished?.Invoke();
}
catch(ThreadAbortException) { }
catch(ThreadAbortException) {}
catch(Exception ex)
{
if(Debugger.IsAttached) throw;
if(Debugger.IsAttached)
throw;
Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}");
#if DEBUG
#if DEBUG
Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException);
#endif
#endif
}
}
@@ -430,17 +505,18 @@ namespace apprepodbmgr.Core
if(!File.Exists(Context.Path))
{
Failed?.Invoke("Specified file cannot be found");
return;
}
if(!Directory.Exists(Settings.Current.TemporaryFolder))
{
Failed?.Invoke("Temporary folder cannot be found");
return;
}
string tmpFolder = Context.UserExtracting
? Context.TmpFolder
string tmpFolder = Context.UserExtracting ? Context.TmpFolder
: Path.Combine(Settings.Current.TemporaryFolder, Path.GetRandomFileName());
try
@@ -449,10 +525,11 @@ namespace apprepodbmgr.Core
Context.TmpFolder = tmpFolder;
}
catch(ThreadAbortException) { }
catch(ThreadAbortException) {}
catch(Exception)
{
if(Debugger.IsAttached) throw;
if(Debugger.IsAttached)
throw;
Failed?.Invoke("Cannot create temporary folder");
}
@@ -460,105 +537,125 @@ namespace apprepodbmgr.Core
try
{
// If it's a ZIP file not created by Mac OS X, use DotNetZip to uncompress (unar freaks out or corrupts certain ZIP features)
if(Context.ArchiveFormat == "Zip" && !Context.UnzipWithUnAr && Context.UsableDotNetZip)
if(Context.ArchiveFormat == "Zip" &&
!Context.UnzipWithUnAr &&
Context.UsableDotNetZip)
try
{
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
ZipFile zf = ZipFile.Read(Context.Path, new ReadOptions {Encoding = Encoding.UTF8});
#endif
var zf = ZipFile.Read(Context.Path, new ReadOptions
{
Encoding = Encoding.UTF8
});
zf.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently;
zf.ExtractProgress += Zf_ExtractProgress;
zipCounter = 0;
zipCurrentEntryName = "";
zf.ExtractAll(tmpFolder);
}
catch(ThreadAbortException) { }
catch(ThreadAbortException) {}
catch(Exception ex)
{
if(Debugger.IsAttached) throw;
if(Debugger.IsAttached)
throw;
Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}");
#if DEBUG
#if DEBUG
Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException);
#endif
#endif
}
else
{
if(!Context.UnarUsable)
{
Failed?.Invoke("The UnArchiver is not correctly installed");
return;
}
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
#endif
Context.UnarProcess = new Process
{
StartInfo =
{
FileName = Settings.Current.UnArchiverPath,
CreateNoWindow = true,
FileName = Settings.Current.UnArchiverPath,
CreateNoWindow = true,
RedirectStandardOutput = true,
UseShellExecute = false,
Arguments =
$"-o \"\"\"{tmpFolder}\"\"\" -r -D -k hidden \"\"\"{Context.Path}\"\"\""
UseShellExecute = false,
Arguments = $"-o \"\"\"{tmpFolder}\"\"\" -r -D -k hidden \"\"\"{Context.Path}\"\"\""
}
};
long counter = 0;
Context.UnarProcess.OutputDataReceived += (sender, e) =>
{
counter++;
UpdateProgress2?.Invoke("", e.Data, counter, Context.NoFilesInArchive);
};
Context.UnarProcess.Start();
Context.UnarProcess.BeginOutputReadLine();
Context.UnarProcess.WaitForExit();
Context.UnarProcess.Close();
Context.UnarProcess = null;
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.ExtractArchive(): Took {0} seconds to extract archive contents using UnAr",
stopwatch.Elapsed.TotalSeconds);
#endif
#endif
Finished?.Invoke();
}
}
catch(ThreadAbortException) { }
catch(ThreadAbortException) {}
catch(Exception ex)
{
if(Debugger.IsAttached) throw;
if(Debugger.IsAttached)
throw;
Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}");
#if DEBUG
#if DEBUG
Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException);
#endif
#endif
}
}
static void Zf_ExtractProgress(object sender, ExtractProgressEventArgs e)
{
if(e.CurrentEntry != null && e.CurrentEntry.FileName != zipCurrentEntryName)
if(e.CurrentEntry != null &&
e.CurrentEntry.FileName != zipCurrentEntryName)
{
zipCurrentEntryName = e.CurrentEntry.FileName;
zipCounter++;
}
if(UpdateProgress != null && e.CurrentEntry != null && e.EntriesTotal > 0)
if(UpdateProgress != null &&
e.CurrentEntry != null &&
e.EntriesTotal > 0)
UpdateProgress("Extracting...", e.CurrentEntry.FileName, zipCounter, e.EntriesTotal);
if(UpdateProgress2 != null && e.TotalBytesToTransfer > 0)
if(UpdateProgress2 != null &&
e.TotalBytesToTransfer > 0)
UpdateProgress2($"{e.BytesTransferred / (double)e.TotalBytesToTransfer:P}",
$"{e.BytesTransferred} / {e.TotalBytesToTransfer}", e.BytesTransferred,
e.TotalBytesToTransfer);
if(e.EventType != ZipProgressEventType.Extracting_AfterExtractAll || Finished == null) return;
#if DEBUG
if(e.EventType != ZipProgressEventType.Extracting_AfterExtractAll ||
Finished == null)
return;
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.Zf_ExtractProgress(): Took {0} seconds to extract archive contents using DotNetZip",
stopwatch.Elapsed.TotalSeconds);
#endif
#endif
Finished();
}
@@ -569,34 +666,39 @@ namespace apprepodbmgr.Core
if(string.IsNullOrWhiteSpace(Context.Path))
{
Failed?.Invoke("Destination cannot be empty");
return;
}
if(Directory.Exists(Context.Path))
{
Failed?.Invoke("Destination cannot be a folder");
return;
}
if(Context.DbInfo.Id == 0)
{
Failed?.Invoke("Operating system must be set");
return;
}
if(dbCore.DbOps.HasSymlinks(Context.DbInfo.Id))
{
Failed?.Invoke("Cannot create symbolic links on ZIP files");
return;
}
if(!Context.UsableDotNetZip)
{
Failed?.Invoke("Cannot create ZIP files");
return;
}
ZipFile zf = new ZipFile(Context.Path, Encoding.UTF8)
var zf = new ZipFile(Context.Path, Encoding.UTF8)
{
CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression,
CompressionMethod = CompressionMethod.Deflate,
@@ -605,6 +707,7 @@ namespace apprepodbmgr.Core
UseZip64WhenSaving = Zip64Option.AsNecessary,
SortEntriesBeforeSaving = true
};
zf.SaveProgress += Zf_SaveProgress;
UpdateProgress?.Invoke("", "Asking DB for files...", 1, 100);
@@ -617,10 +720,11 @@ namespace apprepodbmgr.Core
UpdateProgress?.Invoke("", "Creating folders...", 3, 100);
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
#endif
long counter = 0;
foreach(DbFolder folder in folders)
{
UpdateProgress2?.Invoke("", folder.Path, counter, folders.Count);
@@ -634,17 +738,18 @@ namespace apprepodbmgr.Core
counter++;
}
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.CompressTo(): Took {0} seconds to add folders to ZIP",
stopwatch.Elapsed.TotalSeconds);
#endif
#endif
counter = 3;
Context.Hashes = new Dictionary<string, DbAppFile>();
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
#endif
foreach(DbAppFile file in files)
{
UpdateProgress?.Invoke("", $"Adding {file.Path}...", counter, 3 + files.Count);
@@ -660,37 +765,42 @@ namespace apprepodbmgr.Core
counter++;
}
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.CompressTo(): Took {0} seconds to add files to ZIP",
stopwatch.Elapsed.TotalSeconds);
stopwatch.Restart();
#endif
#endif
zipCounter = 0;
zipCurrentEntryName = "";
zf.Save();
}
catch(ThreadAbortException) { }
catch(ThreadAbortException) {}
catch(Exception ex)
{
if(Debugger.IsAttached) throw;
if(Debugger.IsAttached)
throw;
Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}");
#if DEBUG
#if DEBUG
Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException);
#endif
#endif
}
}
static Stream Zf_HandleOpen(string entryName)
{
DbAppFile file;
if(!Context.Hashes.TryGetValue(entryName, out file))
if(!Context.Hashes.TryGetValue(entryName.Replace('/', '\\'), out file))
throw new ArgumentException("Cannot find requested zip entry in hashes dictionary");
// Special case for empty file, as it seems to crash when SharpCompress tries to unLZMA it.
if(file.Length == 0) return new MemoryStream();
if(file.Length == 0)
return new MemoryStream();
Stream zStream = null;
string repoPath;
@@ -703,6 +813,7 @@ namespace apprepodbmgr.Core
repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[3].ToString(),
file.Sha256[4].ToString(), file.Sha256 + ".gz");
algorithm = AlgoEnum.GZip;
}
else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
@@ -713,6 +824,7 @@ namespace apprepodbmgr.Core
repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[3].ToString(),
file.Sha256[4].ToString(), file.Sha256 + ".bz2");
algorithm = AlgoEnum.BZip2;
}
else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
@@ -723,6 +835,7 @@ namespace apprepodbmgr.Core
repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[3].ToString(),
file.Sha256[4].ToString(), file.Sha256 + ".lzma");
algorithm = AlgoEnum.LZMA;
}
else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
@@ -733,50 +846,58 @@ namespace apprepodbmgr.Core
repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[3].ToString(),
file.Sha256[4].ToString(), file.Sha256 + ".lz");
algorithm = AlgoEnum.LZip;
}
else throw new ArgumentException($"Cannot find file with hash {file.Sha256} in the repository");
else
throw new ArgumentException($"Cannot find file with hash {file.Sha256} in the repository");
FileStream inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read);
var inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read);
switch(algorithm)
{
case AlgoEnum.GZip:
zStream = new GZipStream(inFs, CompressionMode.Decompress);
break;
case AlgoEnum.BZip2:
zStream = new BZip2Stream(inFs, CompressionMode.Decompress);
break;
case AlgoEnum.LZMA:
byte[] properties = new byte[5];
inFs.Read(properties, 0, 5);
inFs.Seek(8, SeekOrigin.Current);
zStream = new LzmaStream(properties, inFs, inFs.Length - 13, file.Length);
break;
case AlgoEnum.LZip:
zStream = new LZipStream(inFs, CompressionMode.Decompress);
break;
}
return zStream;
}
static void Zf_HandleClose(string entryName, Stream stream)
{
stream.Close();
}
static void Zf_HandleClose(string entryName, Stream stream) => stream.Close();
static void Zf_SaveProgress(object sender, SaveProgressEventArgs e)
{
if(e.CurrentEntry != null && e.CurrentEntry.FileName != zipCurrentEntryName)
if(e.CurrentEntry != null &&
e.CurrentEntry.FileName != zipCurrentEntryName)
{
zipCurrentEntryName = e.CurrentEntry.FileName;
zipCounter++;
}
if(UpdateProgress != null && e.CurrentEntry != null && e.EntriesTotal > 0)
if(UpdateProgress != null &&
e.CurrentEntry != null &&
e.EntriesTotal > 0)
UpdateProgress("Compressing...", e.CurrentEntry.FileName, zipCounter, e.EntriesTotal);
if(UpdateProgress2 != null && e.TotalBytesToTransfer > 0)
if(UpdateProgress2 != null &&
e.TotalBytesToTransfer > 0)
UpdateProgress2($"{e.BytesTransferred / (double)e.TotalBytesToTransfer:P}",
$"{e.BytesTransferred} / {e.TotalBytesToTransfer}", e.BytesTransferred,
e.TotalBytesToTransfer);
@@ -785,14 +906,17 @@ namespace apprepodbmgr.Core
{
case ZipProgressEventType.Error_Saving:
Failed?.Invoke("An error occurred creating ZIP file.");
break;
case ZipProgressEventType.Saving_Completed when Finished != null:
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.Zf_SaveProgress(): Took {0} seconds to compress files to ZIP",
stopwatch.Elapsed.TotalSeconds);
#endif
#endif
Finished();
break;
}
}

View File

@@ -40,49 +40,54 @@ namespace apprepodbmgr.Core
{
try
{
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
#endif
dbCore.DbOps.GetAllApps(out List<DbEntry> apps);
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.GetAllApps(): Took {0} seconds to get apps from database",
stopwatch.Elapsed.TotalSeconds);
#endif
#endif
if(AddApp != null)
{
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
#endif
int counter = 0;
// TODO: Check file name and existence
foreach(DbEntry app in apps)
{
UpdateProgress?.Invoke("Populating apps table", $"{app.Developer} {app.Product}", counter,
apps.Count);
AddApp?.Invoke(app);
counter++;
}
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.GetAllApps(): Took {0} seconds to add apps to the GUI",
stopwatch.Elapsed.TotalSeconds);
#endif
#endif
}
Finished?.Invoke();
}
catch(ThreadAbortException) { }
catch(ThreadAbortException) {}
catch(Exception ex)
{
if(Debugger.IsAttached) throw;
if(Debugger.IsAttached)
throw;
Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}");
#if DEBUG
#if DEBUG
Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException);
#endif
#endif
}
}
@@ -91,9 +96,9 @@ namespace apprepodbmgr.Core
try
{
long counter = 0;
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
#endif
Dictionary<string, DbAppFile> knownFiles = new Dictionary<string, DbAppFile>();
bool unknownFile = false;
@@ -105,6 +110,7 @@ namespace apprepodbmgr.Core
{
AddFileForApp(kvp.Key, kvp.Value.Sha256, true, kvp.Value.Crack);
counter++;
continue;
}
@@ -118,43 +124,50 @@ namespace apprepodbmgr.Core
counter++;
knownFiles.Add(kvp.Key, kvp.Value);
}
else unknownFile = true;
else
unknownFile = true;
}
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.CheckDbForFiles(): Took {0} seconds to checks for file knowledge in the DB",
stopwatch.Elapsed.TotalSeconds);
stopwatch.Restart();
#endif
#endif
if(knownFiles.Count == 0 || unknownFile)
{
Finished?.Invoke();
return;
}
UpdateProgress?.Invoke(null, "Retrieving apps from database", counter, Context.Hashes.Count);
dbCore.DbOps.GetAllApps(out List<DbEntry> apps);
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.CheckDbForFiles(): Took {0} seconds get all apps from DB",
stopwatch.Elapsed.TotalSeconds);
#endif
#endif
if(apps != null && apps.Count > 0)
if(apps != null &&
apps.Count > 0)
{
DbEntry[] appsArray = new DbEntry[apps.Count];
apps.CopyTo(appsArray);
long appCounter = 0;
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
#endif
foreach(DbEntry app in appsArray)
{
UpdateProgress?.Invoke(null, $"Check application id {app.Id}", appCounter, appsArray.Length);
counter = 0;
foreach(KeyValuePair<string, DbAppFile> kvp in knownFiles)
{
UpdateProgress2?.Invoke(null, $"Checking for file {kvp.Value.Path}", counter,
@@ -162,7 +175,8 @@ namespace apprepodbmgr.Core
if(!dbCore.DbOps.ExistsFileInApp(kvp.Value.Sha256, app.Id))
{
if(apps.Contains(app)) apps.Remove(app);
if(apps.Contains(app))
apps.Remove(app);
// If one file is missing, the rest don't matter
break;
@@ -171,13 +185,15 @@ namespace apprepodbmgr.Core
counter++;
}
if(apps.Count == 0) break; // No apps left
if(apps.Count == 0)
break; // No apps left
}
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.CheckDbForFiles(): Took {0} seconds correlate all files with all known applications",
stopwatch.Elapsed.TotalSeconds);
#endif
#endif
}
if(AddApp != null)
@@ -186,15 +202,16 @@ namespace apprepodbmgr.Core
Finished?.Invoke();
}
catch(ThreadAbortException) { }
catch(ThreadAbortException) {}
catch(Exception ex)
{
if(Debugger.IsAttached) throw;
if(Debugger.IsAttached)
throw;
Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}");
#if DEBUG
#if DEBUG
Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException);
#endif
#endif
}
}
@@ -203,16 +220,16 @@ namespace apprepodbmgr.Core
try
{
long counter = 0;
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
#endif
foreach(KeyValuePair<string, DbAppFile> kvp in Context.Hashes)
{
UpdateProgress?.Invoke(null, "Adding files to database", counter, Context.Hashes.Count);
if(!dbCore.DbOps.ExistsFile(kvp.Value.Sha256))
{
DbFile file = new DbFile
var file = new DbFile
{
Sha256 = kvp.Value.Sha256,
ClamTime = null,
@@ -222,6 +239,7 @@ namespace apprepodbmgr.Core
HasVirus = null,
VirusTotalTime = null
};
dbCore.DbOps.AddFile(file);
AddFile?.Invoke(file);
@@ -229,21 +247,23 @@ namespace apprepodbmgr.Core
counter++;
}
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.AddFilesToDb(): Took {0} seconds to add all files to the database",
stopwatch.Elapsed.TotalSeconds);
#endif
#endif
UpdateProgress?.Invoke(null, "Adding application information", counter, Context.Hashes.Count);
dbCore.DbOps.AddApp(Context.DbInfo, out Context.DbInfo.Id);
UpdateProgress?.Invoke(null, "Creating application table", counter, Context.Hashes.Count);
dbCore.DbOps.CreateTableForApp(Context.DbInfo.Id);
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
#endif
counter = 0;
foreach(KeyValuePair<string, DbAppFile> kvp in Context.Hashes)
{
UpdateProgress?.Invoke(null, "Adding files to application in database", counter,
@@ -253,13 +273,16 @@ namespace apprepodbmgr.Core
counter++;
}
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.AddFilesToDb(): Took {0} seconds to add all files to the application in the database",
stopwatch.Elapsed.TotalSeconds);
stopwatch.Restart();
#endif
#endif
counter = 0;
foreach(KeyValuePair<string, DbFolder> kvp in Context.FoldersDict)
{
UpdateProgress?.Invoke(null, "Adding folders to application in database", counter,
@@ -269,14 +292,18 @@ namespace apprepodbmgr.Core
counter++;
}
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.AddFilesToDb(): Took {0} seconds to add all folders to the database",
stopwatch.Elapsed.TotalSeconds);
stopwatch.Restart();
#endif
#endif
counter = 0;
if(Context.SymlinksDict.Count > 0) dbCore.DbOps.CreateSymlinkTableForOs(Context.DbInfo.Id);
if(Context.SymlinksDict.Count > 0)
dbCore.DbOps.CreateSymlinkTableForOs(Context.DbInfo.Id);
foreach(KeyValuePair<string, string> kvp in Context.SymlinksDict)
{
@@ -287,23 +314,25 @@ namespace apprepodbmgr.Core
counter++;
}
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.AddFilesToDb(): Took {0} seconds to add all symbolic links to the database",
stopwatch.Elapsed.TotalSeconds);
#endif
#endif
Finished?.Invoke();
}
catch(ThreadAbortException) { }
catch(ThreadAbortException) {}
catch(Exception ex)
{
if(Debugger.IsAttached) throw;
if(Debugger.IsAttached)
throw;
Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}");
#if DEBUG
#if DEBUG
Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException);
#endif
#endif
}
}
@@ -317,16 +346,19 @@ namespace apprepodbmgr.Core
if(string.IsNullOrEmpty(Settings.Current.DatabasePath))
{
Failed?.Invoke("No database file specified");
return;
}
dbCore = new SQLite();
if(File.Exists(Settings.Current.DatabasePath))
{
if(!dbCore.OpenDb(Settings.Current.DatabasePath, null, null, null))
{
Failed?.Invoke("Could not open database, correct file selected?");
dbCore = null;
return;
}
}
@@ -336,6 +368,7 @@ namespace apprepodbmgr.Core
{
Failed?.Invoke("Could not create database, correct file selected?");
dbCore = null;
return;
}
@@ -343,32 +376,33 @@ namespace apprepodbmgr.Core
{
Failed?.Invoke("Could not open database, correct file selected?");
dbCore = null;
return;
}
}
Finished?.Invoke();
}
catch(ThreadAbortException) { }
catch(ThreadAbortException) {}
catch(Exception ex)
{
if(Debugger.IsAttached) throw;
if(Debugger.IsAttached)
throw;
Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}");
#if DEBUG
#if DEBUG
Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException);
#endif
#endif
}
}
public static void CloseDB()
{
dbCore?.CloseDb();
}
public static void CloseDB() => dbCore?.CloseDb();
public static void RemoveApp(long id, string mdid)
{
if(id == 0 || string.IsNullOrWhiteSpace(mdid)) return;
if(id == 0 ||
string.IsNullOrWhiteSpace(mdid))
return;
dbCore.DbOps.RemoveApp(id);
}
@@ -381,12 +415,13 @@ namespace apprepodbmgr.Core
const ulong PAGE = 2500;
ulong offset = 0;
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
#endif
while(dbCore.DbOps.GetFiles(out List<DbFile> files, offset, PAGE))
{
if(files.Count == 0) break;
if(files.Count == 0)
break;
UpdateProgress?.Invoke(null, $"Loaded file {offset} of {count}", (long)offset, (long)count);
@@ -394,23 +429,25 @@ namespace apprepodbmgr.Core
offset += PAGE;
}
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.GetFilesFromDb(): Took {0} seconds to get all files from the database",
stopwatch.Elapsed.TotalSeconds);
#endif
#endif
Finished?.Invoke();
}
catch(ThreadAbortException) { }
catch(ThreadAbortException) {}
catch(Exception ex)
{
if(Debugger.IsAttached) throw;
if(Debugger.IsAttached)
throw;
Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}");
#if DEBUG
#if DEBUG
Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException);
#endif
#endif
}
}
@@ -422,21 +459,19 @@ namespace apprepodbmgr.Core
Finished?.Invoke();
}
catch(ThreadAbortException) { }
catch(ThreadAbortException) {}
catch(Exception ex)
{
if(Debugger.IsAttached) throw;
if(Debugger.IsAttached)
throw;
Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}");
#if DEBUG
#if DEBUG
Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException);
#endif
#endif
}
}
public static DbFile GetDBFile(string hash)
{
return dbCore.DbOps.GetFile(hash);
}
public static DbFile GetDBFile(string hash) => dbCore.DbOps.GetFile(hash);
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -40,15 +40,16 @@ namespace apprepodbmgr.Core
static int zipCounter;
static string zipCurrentEntryName;
#if DEBUG
static Stopwatch stopwatch = new Stopwatch();
#endif
#if DEBUG
static readonly Stopwatch stopwatch = new Stopwatch();
#endif
static string Stringify(byte[] hash)
{
StringBuilder hashOutput = new StringBuilder();
var hashOutput = new StringBuilder();
foreach(byte h in hash) hashOutput.Append(h.ToString("x2"));
foreach(byte h in hash)
hashOutput.Append(h.ToString("x2"));
return hashOutput.ToString();
}
@@ -58,6 +59,7 @@ namespace apprepodbmgr.Core
if(string.IsNullOrWhiteSpace(Settings.Current.UnArchiverPath))
{
Failed?.Invoke("unar path is not set.");
return;
}
@@ -71,12 +73,14 @@ namespace apprepodbmgr.Core
if(!File.Exists(unarPath))
{
Failed?.Invoke($"Cannot find unar executable at {unarPath}.");
return;
}
if(!File.Exists(lsarPath))
{
Failed?.Invoke("Cannot find unar executable.");
return;
}
@@ -84,7 +88,7 @@ namespace apprepodbmgr.Core
try
{
Process unarProcess = new Process
var unarProcess = new Process
{
StartInfo =
{
@@ -94,6 +98,7 @@ namespace apprepodbmgr.Core
UseShellExecute = false
}
};
unarProcess.Start();
unarProcess.WaitForExit();
unarOut = unarProcess.StandardOutput.ReadToEnd();
@@ -101,12 +106,13 @@ namespace apprepodbmgr.Core
catch
{
Failed?.Invoke("Cannot run unar.");
return;
}
try
{
Process lsarProcess = new Process
var lsarProcess = new Process
{
StartInfo =
{
@@ -116,6 +122,7 @@ namespace apprepodbmgr.Core
UseShellExecute = false
}
};
lsarProcess.Start();
lsarProcess.WaitForExit();
lsarOut = lsarProcess.StandardOutput.ReadToEnd();
@@ -123,22 +130,25 @@ namespace apprepodbmgr.Core
catch
{
Failed?.Invoke("Cannot run lsar.");
return;
}
if(!unarOut.StartsWith("unar ", StringComparison.CurrentCulture))
{
Failed?.Invoke("Not the correct unar executable");
return;
}
if(!lsarOut.StartsWith("lsar ", StringComparison.CurrentCulture))
{
Failed?.Invoke("Not the correct unar executable");
return;
}
Process versionProcess = new Process
var versionProcess = new Process
{
StartInfo =
{
@@ -149,6 +159,7 @@ namespace apprepodbmgr.Core
Arguments = "-v"
}
};
versionProcess.Start();
versionProcess.WaitForExit();

View File

@@ -55,7 +55,8 @@ namespace apprepodbmgr.Core
{
Task.Run(async () =>
{
vt = new VirusTotal(key);
vt = new VirusTotal(key);
report =
await vt.GetFileReportAsync("b82758fc5f737a58078d3c60e2798a70d895443a86aa39adf52dec70e98c2bed");
}).Wait();
@@ -63,6 +64,7 @@ namespace apprepodbmgr.Core
catch(Exception ex)
{
Failed?.Invoke(ex.InnerException?.Message);
return false;
}
@@ -78,7 +80,8 @@ namespace apprepodbmgr.Core
{
Task.Run(async () =>
{
vt = new VirusTotal(key);
vt = new VirusTotal(key);
report =
await vt.GetFileReportAsync("b82758fc5f737a58078d3c60e2798a70d895443a86aa39adf52dec70e98c2bed");
}).Wait();
@@ -86,13 +89,17 @@ namespace apprepodbmgr.Core
catch(Exception ex)
{
Failed?.Invoke(ex.InnerException?.Message);
return false;
}
if(report == null || report.MD5 != "0bf60adb1435639a42b490e7e80d25c7") return false;
if(report == null ||
report.MD5 != "0bf60adb1435639a42b490e7e80d25c7")
return false;
vTotal = vt;
Context.VirusTotalEnabled = true;
return true;
}
@@ -103,41 +110,50 @@ namespace apprepodbmgr.Core
if(!Context.VirusTotalEnabled)
{
Failed?.Invoke("VirusTotal is not usable");
return;
}
if(vTotal == null) Failed?.Invoke("VirusTotal is not initalized");
if(vTotal == null)
Failed?.Invoke("VirusTotal is not initalized");
FileReport fResult = null;
UpdateProgress?.Invoke("Requesting existing report to VirusTotal", null, 0, 0);
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
Task.Run(async () => { fResult = await vTotal.GetFileReportAsync(file.Sha256); }).Wait();
#if DEBUG
#endif
Task.Run(async () =>
{
fResult = await vTotal.GetFileReportAsync(file.Sha256);
}).Wait();
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.VirusTotalFileFromRepo({0}): VirusTotal took {1} seconds to answer for SHA256 request",
file, stopwatch.Elapsed.TotalSeconds);
#endif
#endif
if(fResult.ResponseCode == FileReportResponseCode.NotPresent)
{
Failed?.Invoke(fResult.VerboseMsg);
return;
}
if(fResult.ResponseCode != FileReportResponseCode.Queued)
{
if(fResult.ResponseCode == FileReportResponseCode.Present)
if(fResult.ResponseCode == FileReportResponseCode.Present)
if(fResult.Positives > 0)
{
file.HasVirus = true;
if(fResult.Scans != null)
foreach(KeyValuePair<string, ScanEngine> engine in fResult.Scans)
{
if(!engine.Value.Detected) continue;
if(!engine.Value.Detected)
continue;
file.Virus = engine.Value.Result;
file.VirusTotalTime = engine.Value.Update;
@@ -175,6 +191,7 @@ namespace apprepodbmgr.Core
file.Sha256[1].ToString(), file.Sha256[2].ToString(),
file.Sha256[3].ToString(), file.Sha256[4].ToString(),
file.Sha256 + ".gz");
algorithm = AlgoEnum.GZip;
}
else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
@@ -186,6 +203,7 @@ namespace apprepodbmgr.Core
file.Sha256[1].ToString(), file.Sha256[2].ToString(),
file.Sha256[3].ToString(), file.Sha256[4].ToString(),
file.Sha256 + ".bz2");
algorithm = AlgoEnum.BZip2;
}
else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
@@ -197,6 +215,7 @@ namespace apprepodbmgr.Core
file.Sha256[1].ToString(), file.Sha256[2].ToString(),
file.Sha256[3].ToString(), file.Sha256[4].ToString(),
file.Sha256 + ".lzma");
algorithm = AlgoEnum.LZMA;
}
else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
@@ -208,77 +227,89 @@ namespace apprepodbmgr.Core
file.Sha256[1].ToString(), file.Sha256[2].ToString(),
file.Sha256[3].ToString(), file.Sha256[4].ToString(),
file.Sha256 + ".lz");
algorithm = AlgoEnum.LZip;
}
else
{
Failed?.Invoke($"Cannot find file with hash {file.Sha256} in the repository");
return;
}
UpdateProgress?.Invoke("Uncompressing file...", null, 0, 0);
FileStream inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read);
Stream zStream = null;
var inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read);
Stream zStream = null;
switch(algorithm)
{
case AlgoEnum.GZip:
zStream = new GZipStream(inFs, CompressionMode.Decompress);
break;
case AlgoEnum.BZip2:
zStream = new BZip2Stream(inFs, CompressionMode.Decompress);
break;
case AlgoEnum.LZMA:
byte[] properties = new byte[5];
inFs.Read(properties, 0, 5);
inFs.Seek(8, SeekOrigin.Current);
zStream = new LzmaStream(properties, inFs, inFs.Length - 13, file.Length);
break;
case AlgoEnum.LZip:
zStream = new LZipStream(inFs, CompressionMode.Decompress);
break;
}
ScanResult sResult = null;
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
#endif
// Cannot use zStream directly, VirusTotal.NET requests the size *sigh*
string tmpFile = Path.Combine(Settings.Current.TemporaryFolder, Path.GetTempFileName());
FileStream outFs = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite);
string tmpFile = Path.Combine(Settings.Current.TemporaryFolder, Path.GetTempFileName());
var outFs = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite);
zStream?.CopyTo(outFs);
zStream?.Close();
outFs.Seek(0, SeekOrigin.Begin);
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.VirusTotalFileFromRepo({0}): Uncompressing took {1} seconds", file,
stopwatch.Elapsed.TotalSeconds);
#endif
#endif
UpdateProgress?.Invoke("Uploading file to VirusTotal...", null, 0, 0);
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
#endif
Task.Run(async () =>
{
sResult = await vTotal.ScanFileAsync(outFs, file.Sha256); // Keep filename private, sorry!
}).Wait();
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.VirusTotalFileFromRepo({0}): Upload to VirusTotal took {1} seconds", file,
stopwatch.Elapsed.TotalSeconds);
#endif
#endif
outFs.Close();
File.Delete(tmpFile);
if(sResult == null || sResult.ResponseCode == ScanFileResponseCode.Error)
if(sResult == null ||
sResult.ResponseCode == ScanFileResponseCode.Error)
{
if(sResult == null) Failed?.Invoke("Cannot send file to VirusTotal");
else Failed(sResult.VerboseMsg);
if(sResult == null)
Failed?.Invoke("Cannot send file to VirusTotal");
else
Failed(sResult.VerboseMsg);
return;
}
@@ -286,47 +317,60 @@ namespace apprepodbmgr.Core
// Seems that we are faster than them, getting a lot of "not queued" responses...
Thread.Sleep(2500);
Task.Run(async () => { fResult = await vTotal.GetFileReportAsync(file.Sha256); }).Wait();
Task.Run(async () =>
{
fResult = await vTotal.GetFileReportAsync(file.Sha256);
}).Wait();
}
UpdateProgress?.Invoke("Waiting for VirusTotal analysis...", null, 0, 0);
#if DEBUG
#if DEBUG
stopwatch.Restart();
#endif
#endif
int counter = 0;
while(fResult.ResponseCode == FileReportResponseCode.Queued)
{
// Timeout...
if(counter == 10) break;
if(counter == 10)
break;
// Wait 15 seconds so we fall in the 4 requests/minute
Thread.Sleep(15000);
Task.Run(async () => { fResult = await vTotal.GetFileReportAsync(file.Sha256); }).Wait();
Task.Run(async () =>
{
fResult = await vTotal.GetFileReportAsync(file.Sha256);
}).Wait();
counter++;
}
#if DEBUG
#if DEBUG
stopwatch.Stop();
Console.WriteLine("Core.VirusTotalFileFromRepo({0}): VirusTotal took {1} seconds to do the analysis",
file, stopwatch.Elapsed.TotalSeconds);
#endif
#endif
if(fResult.ResponseCode != FileReportResponseCode.Present)
{
Failed?.Invoke(fResult.VerboseMsg);
return;
}
if(fResult.Positives > 0)
{
file.HasVirus = true;
if(fResult.Scans == null) return;
if(fResult.Scans == null)
return;
foreach(KeyValuePair<string, ScanEngine> engine in fResult.Scans)
{
if(!engine.Value.Detected) continue;
if(!engine.Value.Detected)
continue;
file.Virus = engine.Value.Result;
file.VirusTotalTime = engine.Value.Update;
@@ -353,9 +397,9 @@ namespace apprepodbmgr.Core
catch(Exception ex)
{
Failed?.Invoke($"Exception {ex.InnerException.Message} when calling VirusTotal");
#if DEBUG
#if DEBUG
Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException);
#endif
#endif
}
}
}

View File

@@ -40,9 +40,12 @@ namespace apprepodbmgr.Eto.Desktop
{
Settings.LoadSettings();
Context.CheckUnar();
if(Settings.Current.UseAntivirus)
{
if(Settings.Current.UseClamd) Workers.InitClamd();
if(Settings.Current.UseClamd)
Workers.InitClamd();
if(Settings.Current.UseVirusTotal)
Context.VirusTotalEnabled = Workers.InitVirusTotal(Settings.Current.VirusTotalKey);
}
@@ -52,4 +55,4 @@ namespace apprepodbmgr.Eto.Desktop
new Application(Platform.Detect).Run(new frmMain());
}
}
}
}

View File

@@ -31,139 +31,153 @@ using Schemas;
namespace apprepodbmgr.Eto
{
class DBEntryForEto
internal class DBEntryForEto
{
DbEntry _item;
readonly DbEntry _item;
public DBEntryForEto(DbEntry item)
{
_item = item;
}
public DBEntryForEto(DbEntry item) => _item = item;
public long id
{
get { return _item.Id; }
set { }
get => _item.Id;
set {}
}
public string developer
{
get { return _item.Developer; }
set { }
get => _item.Developer;
set {}
}
public string product
{
get { return _item.Product; }
set { }
get => _item.Product;
set {}
}
public string version
{
get { return _item.Version; }
set { }
get => _item.Version;
set {}
}
public string languages
{
get { return _item.Languages; }
set { }
get => _item.Languages;
set {}
}
public string architecture
{
get { return _item.Architecture; }
set { }
get => _item.Architecture;
set {}
}
public string targetos
{
get { return _item.TargetOs; }
set { }
get => _item.TargetOs;
set {}
}
public string format
{
get { return _item.Format; }
set { }
get => _item.Format;
set {}
}
public string description
{
get { return _item.Description; }
set { }
get => _item.Description;
set {}
}
public bool oem
{
get { return _item.Oem; }
set { }
get => _item.Oem;
set {}
}
public bool upgrade
{
get { return _item.Upgrade; }
set { }
get => _item.Upgrade;
set {}
}
public bool update
{
get { return _item.Update; }
set { }
get => _item.Update;
set {}
}
public bool source
{
get { return _item.Source; }
set { }
get => _item.Source;
set {}
}
public bool files
{
get { return _item.Files; }
set { }
get => _item.Files;
set {}
}
public bool Installer
{
get { return _item.Installer; }
set { }
get => _item.Installer;
set {}
}
public byte[] xml
{
get { return _item.Xml; }
set { }
get => _item.Xml;
set {}
}
public byte[] json
{
get { return _item.Json; }
set { }
get => _item.Json;
set {}
}
public string mdid
{
get { return _item.Mdid; }
set { }
get => _item.Mdid;
set {}
}
public DbEntry original
{
get { return _item; }
set { }
get => _item;
set {}
}
}
class StringEntry
internal class StringEntry
{
public string str { get; set; }
}
class BarcodeEntry
internal class BarcodeEntry
{
public string code { get; set; }
public BarcodeTypeType type { get; set; }
}
class DiscEntry
internal class DiscEntry
{
public string path { get; set; }
public OpticalDiscType disc { get; set; }
}
class DiskEntry
internal class DiskEntry
{
public string path { get; set; }
public BlockMediaType disk { get; set; }
}
class TargetOsEntry
internal class TargetOsEntry
{
public string name { get; set; }
public string name { get; set; }
public string version { get; set; }
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -46,9 +46,12 @@ namespace apprepodbmgr.Eto
public void FillFields()
{
if(Metadata == null) return;
if(Metadata == null)
return;
if(Metadata.Type != null)
txtType.Text = Metadata.Type;
if(Metadata.Type != null) txtType.Text = Metadata.Type;
if(Metadata.CreationDateSpecified)
{
chkCreationDate.Checked = true;
@@ -70,14 +73,25 @@ namespace apprepodbmgr.Eto
cldBackupDate.Value = Metadata.BackupDate;
}
spClusterSize.Value = Metadata.ClusterSize;
txtClusters.Text = Metadata.Clusters.ToString();
if(Metadata.FilesSpecified) txtFiles.Text = Metadata.Files.ToString();
chkBootable.Checked = Metadata.Bootable;
if(Metadata.VolumeSerial != null) txtSerial.Text = Metadata.VolumeSerial;
if(Metadata.VolumeName != null) txtLabel.Text = Metadata.VolumeName;
if(Metadata.FreeClustersSpecified) txtFreeClusters.Text = Metadata.FreeClusters.ToString();
chkDirty.Checked = Metadata.Dirty;
spClusterSize.Value = Metadata.ClusterSize;
txtClusters.Text = Metadata.Clusters.ToString();
if(Metadata.FilesSpecified)
txtFiles.Text = Metadata.Files.ToString();
chkBootable.Checked = Metadata.Bootable;
if(Metadata.VolumeSerial != null)
txtSerial.Text = Metadata.VolumeSerial;
if(Metadata.VolumeName != null)
txtLabel.Text = Metadata.VolumeName;
if(Metadata.FreeClustersSpecified)
txtFreeClusters.Text = Metadata.FreeClusters.ToString();
chkDirty.Checked = Metadata.Dirty;
if(Metadata.ExpirationDateSpecified)
{
chkExpirationDate.Checked = true;
@@ -92,37 +106,36 @@ namespace apprepodbmgr.Eto
cldEffectiveDate.Value = Metadata.EffectiveDate;
}
if(Metadata.SystemIdentifier != null) txtSysId.Text = Metadata.SystemIdentifier;
if(Metadata.VolumeSetIdentifier != null) txtVolId.Text = Metadata.VolumeSetIdentifier;
if(Metadata.PublisherIdentifier != null) txtPubId.Text = Metadata.PublisherIdentifier;
if(Metadata.DataPreparerIdentifier != null) txtDataId.Text = Metadata.DataPreparerIdentifier;
if(Metadata.ApplicationIdentifier != null) txtAppId.Text = Metadata.ApplicationIdentifier;
if(Metadata.SystemIdentifier != null)
txtSysId.Text = Metadata.SystemIdentifier;
if(Metadata.VolumeSetIdentifier != null)
txtVolId.Text = Metadata.VolumeSetIdentifier;
if(Metadata.PublisherIdentifier != null)
txtPubId.Text = Metadata.PublisherIdentifier;
if(Metadata.DataPreparerIdentifier != null)
txtDataId.Text = Metadata.DataPreparerIdentifier;
if(Metadata.ApplicationIdentifier != null)
txtAppId.Text = Metadata.ApplicationIdentifier;
}
protected void OnChkCreationDateToggled(object sender, EventArgs e)
{
protected void OnChkCreationDateToggled(object sender, EventArgs e) =>
cldCreationDate.Enabled = chkCreationDate.Checked.Value;
}
protected void OnChkModificationDateToggled(object sender, EventArgs e)
{
protected void OnChkModificationDateToggled(object sender, EventArgs e) =>
cldModificationDate.Enabled = chkModificationDate.Checked.Value;
}
protected void OnChkEffectiveDateToggled(object sender, EventArgs e)
{
protected void OnChkEffectiveDateToggled(object sender, EventArgs e) =>
cldEffectiveDate.Enabled = chkEffectiveDate.Checked.Value;
}
protected void OnChkExpirationDateToggled(object sender, EventArgs e)
{
protected void OnChkExpirationDateToggled(object sender, EventArgs e) =>
cldExpirationDate.Enabled = chkExpirationDate.Checked.Value;
}
protected void OnChkBackupDateToggled(object sender, EventArgs e)
{
protected void OnChkBackupDateToggled(object sender, EventArgs e) =>
cldBackupDate.Enabled = chkBackupDate.Checked.Value;
}
protected void OnBtnCancelClicked(object sender, EventArgs e)
{
@@ -135,26 +148,36 @@ namespace apprepodbmgr.Eto
if(string.IsNullOrWhiteSpace(txtType.Text))
MessageBox.Show("Filesystem type cannot be empty", MessageBoxType.Error);
if(spClusterSize.Value < 1) MessageBox.Show("Clusters must be bigger than 0 bytes", MessageBoxType.Error);
if(spClusterSize.Value < 1)
MessageBox.Show("Clusters must be bigger than 0 bytes", MessageBoxType.Error);
if(!long.TryParse(txtClusters.Text, out long temp))
MessageBox.Show("Clusters must be a number", MessageBoxType.Error);
if(temp < 1) MessageBox.Show("Filesystem must have more than 0 clusters", MessageBoxType.Error);
if(temp < 1)
MessageBox.Show("Filesystem must have more than 0 clusters", MessageBoxType.Error);
if(!string.IsNullOrWhiteSpace(txtFiles.Text) && !long.TryParse(txtFiles.Text, out temp))
if(!string.IsNullOrWhiteSpace(txtFiles.Text) &&
!long.TryParse(txtFiles.Text, out temp))
MessageBox.Show("Files must be a number, or empty for unknown", MessageBoxType.Error);
if(!string.IsNullOrWhiteSpace(txtFiles.Text) && temp < 0)
if(!string.IsNullOrWhiteSpace(txtFiles.Text) &&
temp < 0)
MessageBox.Show("Files must be positive", MessageBoxType.Error);
if(!string.IsNullOrWhiteSpace(txtFreeClusters.Text) && !long.TryParse(txtFreeClusters.Text, out temp))
if(!string.IsNullOrWhiteSpace(txtFreeClusters.Text) &&
!long.TryParse(txtFreeClusters.Text, out temp))
MessageBox.Show("Free clusters must be a number or empty for unknown", MessageBoxType.Error);
if(!string.IsNullOrWhiteSpace(txtFreeClusters.Text) && temp < 0)
if(!string.IsNullOrWhiteSpace(txtFreeClusters.Text) &&
temp < 0)
MessageBox.Show("Free clusters must be positive", MessageBoxType.Error);
Metadata = new FileSystemType {Type = txtType.Text};
Metadata = new FileSystemType
{
Type = txtType.Text
};
if(chkCreationDate.Checked.Value)
{
Metadata.CreationDateSpecified = true;
@@ -175,15 +198,21 @@ namespace apprepodbmgr.Eto
Metadata.ClusterSize = (int)spClusterSize.Value;
Metadata.Clusters = long.Parse(txtClusters.Text);
if(!string.IsNullOrWhiteSpace(txtFiles.Text))
{
Metadata.FilesSpecified = true;
Metadata.Files = long.Parse(txtFiles.Text);
}
Metadata.Bootable = chkBootable.Checked.Value;
if(!string.IsNullOrWhiteSpace(txtSerial.Text)) Metadata.VolumeSerial = txtSerial.Text;
if(!string.IsNullOrWhiteSpace(txtLabel.Text)) Metadata.VolumeName = txtLabel.Text;
Metadata.Bootable = chkBootable.Checked.Value;
if(!string.IsNullOrWhiteSpace(txtSerial.Text))
Metadata.VolumeSerial = txtSerial.Text;
if(!string.IsNullOrWhiteSpace(txtLabel.Text))
Metadata.VolumeName = txtLabel.Text;
if(!string.IsNullOrWhiteSpace(txtFreeClusters.Text))
{
Metadata.FreeClustersSpecified = true;
@@ -191,6 +220,7 @@ namespace apprepodbmgr.Eto
}
Metadata.Dirty = chkDirty.Checked.Value;
if(chkExpirationDate.Checked.Value)
{
Metadata.ExpirationDateSpecified = true;
@@ -203,11 +233,20 @@ namespace apprepodbmgr.Eto
Metadata.EffectiveDate = cldEffectiveDate.Value.Value;
}
if(!string.IsNullOrWhiteSpace(txtSysId.Text)) Metadata.SystemIdentifier = txtSysId.Text;
if(!string.IsNullOrWhiteSpace(txtVolId.Text)) Metadata.VolumeSetIdentifier = txtVolId.Text;
if(!string.IsNullOrWhiteSpace(txtPubId.Text)) Metadata.PublisherIdentifier = txtPubId.Text;
if(!string.IsNullOrWhiteSpace(txtDataId.Text)) Metadata.DataPreparerIdentifier = txtDataId.Text;
if(!string.IsNullOrWhiteSpace(txtAppId.Text)) Metadata.ApplicationIdentifier = txtAppId.Text;
if(!string.IsNullOrWhiteSpace(txtSysId.Text))
Metadata.SystemIdentifier = txtSysId.Text;
if(!string.IsNullOrWhiteSpace(txtVolId.Text))
Metadata.VolumeSetIdentifier = txtVolId.Text;
if(!string.IsNullOrWhiteSpace(txtPubId.Text))
Metadata.PublisherIdentifier = txtPubId.Text;
if(!string.IsNullOrWhiteSpace(txtDataId.Text))
Metadata.DataPreparerIdentifier = txtDataId.Text;
if(!string.IsNullOrWhiteSpace(txtAppId.Text))
Metadata.ApplicationIdentifier = txtAppId.Text;
Modified = true;
Close();

View File

@@ -22,9 +22,9 @@ namespace apprepodbmgr.Eto
Panels maximumPanel;
Panels minimumPanel;
List<TargetOsEntry> operatingSystems;
pnlDescription panelDescription;
pnlStrings panelStrings;
pnlVersions panelVersions;
readonly pnlDescription panelDescription;
readonly pnlStrings panelStrings;
readonly pnlVersions panelVersions;
internal string product;
internal string publisher;
List<string> strings;
@@ -75,37 +75,49 @@ namespace apprepodbmgr.Eto
foreach(string file in Context.Executables)
{
FileStream exeStream = new FileStream(file, FileMode.Open, FileAccess.Read);
MZ mzExe = new MZ(exeStream);
NE neExe = new NE(exeStream);
AtariST stExe = new AtariST(exeStream);
LX lxExe = new LX(exeStream);
COFF coffExe = new COFF(exeStream);
PE peExe = new PE(exeStream);
Geos geosExe = new Geos(exeStream);
ELF elfExe = new ELF(exeStream);
var exeStream = new FileStream(file, FileMode.Open, FileAccess.Read);
var mzExe = new MZ(exeStream);
var neExe = new NE(exeStream);
var stExe = new AtariST(exeStream);
var lxExe = new LX(exeStream);
var coffExe = new COFF(exeStream);
var peExe = new PE(exeStream);
var geosExe = new Geos(exeStream);
var elfExe = new ELF(exeStream);
IExecutable recognizedExe;
if(neExe.Recognized) recognizedExe = neExe;
else if(lxExe.Recognized) recognizedExe = lxExe;
else if(peExe.Recognized) recognizedExe = peExe;
else if(mzExe.Recognized) recognizedExe = mzExe;
else if(coffExe.Recognized) recognizedExe = coffExe;
else if(stExe.Recognized) recognizedExe = stExe;
else if(elfExe.Recognized) recognizedExe = elfExe;
else if(geosExe.Recognized) recognizedExe = geosExe;
if(neExe.Recognized)
recognizedExe = neExe;
else if(lxExe.Recognized)
recognizedExe = lxExe;
else if(peExe.Recognized)
recognizedExe = peExe;
else if(mzExe.Recognized)
recognizedExe = mzExe;
else if(coffExe.Recognized)
recognizedExe = coffExe;
else if(stExe.Recognized)
recognizedExe = stExe;
else if(elfExe.Recognized)
recognizedExe = elfExe;
else if(geosExe.Recognized)
recognizedExe = geosExe;
else
{
exeStream.Close();
continue;
}
if(recognizedExe.Strings != null) strings.AddRange(recognizedExe.Strings);
if(recognizedExe.Strings != null)
strings.AddRange(recognizedExe.Strings);
foreach(Architecture exeArch in recognizedExe.Architectures)
{
ArchitecturesTypeArchitecture? arch = ExeArchToSchemaArch(exeArch);
if(arch.HasValue && !architectures.Contains($"{arch.Value}"))
if(arch.HasValue &&
!architectures.Contains($"{arch.Value}"))
architectures.Add($"{arch.Value}");
}
@@ -125,11 +137,13 @@ namespace apprepodbmgr.Eto
versions.Add(exeVersion.FileVersion);
versions.Add(exeVersion.ProductVersion);
version = exeVersion.ProductVersion;
foreach(KeyValuePair<string, Dictionary<string, string>> kvp in exeVersion
.StringsByLanguage)
foreach(KeyValuePair<string, Dictionary<string, string>> kvp in exeVersion.
StringsByLanguage)
{
if(kvp.Value.TryGetValue("CompanyName", out string tmpValue))
developer = tmpValue;
if(kvp.Value.TryGetValue("ProductName", out string tmpValue2))
product = tmpValue2;
}
@@ -143,11 +157,13 @@ namespace apprepodbmgr.Eto
versions.Add(exeVersion.FileVersion);
versions.Add(exeVersion.ProductVersion);
version = exeVersion.ProductVersion;
foreach(KeyValuePair<string, Dictionary<string, string>> kvp in exeVersion
.StringsByLanguage)
foreach(KeyValuePair<string, Dictionary<string, string>> kvp in exeVersion.
StringsByLanguage)
{
if(kvp.Value.TryGetValue("CompanyName", out string tmpValue))
developer = tmpValue;
if(kvp.Value.TryGetValue("ProductName", out string tmpValue2))
product = tmpValue2;
}
@@ -160,12 +176,15 @@ namespace apprepodbmgr.Eto
versions.Add(lxExe.WinVersion.FileVersion);
versions.Add(lxExe.WinVersion.ProductVersion);
version = lxExe.WinVersion.ProductVersion;
foreach(KeyValuePair<string, Dictionary<string, string>> kvp in lxExe
.WinVersion
.StringsByLanguage)
foreach(KeyValuePair<string, Dictionary<string, string>> kvp in lxExe.WinVersion.
StringsByLanguage)
{
if(kvp.Value.TryGetValue("CompanyName", out string tmpValue)) developer = tmpValue;
if(kvp.Value.TryGetValue("ProductName", out string tmpValue2)) product = tmpValue2;
if(kvp.Value.TryGetValue("CompanyName", out string tmpValue))
developer = tmpValue;
if(kvp.Value.TryGetValue("ProductName", out string tmpValue2))
product = tmpValue2;
}
}
@@ -179,8 +198,11 @@ namespace apprepodbmgr.Eto
strings = strings.Distinct().ToList();
strings.Sort();
if(strings.Count == 0 && minimumPanel == Panels.Strings) minimumPanel = Panels.Versions;
else maximumPanel = Panels.Strings;
if(strings.Count == 0 &&
minimumPanel == Panels.Strings)
minimumPanel = Panels.Versions;
else
maximumPanel = Panels.Strings;
panelStrings.treeStrings.DataStore = strings;
versions = versions.Distinct().ToList();
@@ -194,11 +216,13 @@ namespace apprepodbmgr.Eto
foreach(TargetOsEntry osEntry in operatingSystems)
{
if(string.IsNullOrEmpty(osEntry.name)) continue;
if(string.IsNullOrEmpty(osEntry.name))
continue;
osEntriesDictionary.TryGetValue(osEntry.name, out List<string> osvers);
if(osvers == null) osvers = new List<string>();
if(osvers == null)
osvers = new List<string>();
osvers.Add(osEntry.version);
osEntriesDictionary.Remove(osEntry.name);
@@ -206,38 +230,52 @@ namespace apprepodbmgr.Eto
}
operatingSystems = new List<TargetOsEntry>();
foreach(KeyValuePair<string, List<string>> kvp in osEntriesDictionary.OrderBy(t => t.Key))
{
kvp.Value.Sort();
foreach(string s in kvp.Value.Distinct())
operatingSystems.Add(new TargetOsEntry {name = kvp.Key, version = s});
operatingSystems.Add(new TargetOsEntry
{
name = kvp.Key,
version = s
});
}
panelVersions.treeOs.DataStore = operatingSystems;
if(versions.Count > 0 || architectures.Count > 0 || operatingSystems.Count > 0)
if(versions.Count > 0 ||
architectures.Count > 0 ||
operatingSystems.Count > 0)
maximumPanel = Panels.Versions;
}
prgProgress.Visible = false;
btnPrevious.Enabled = false;
switch(minimumPanel)
{
case Panels.Description:
pnlPanel.Content = panelDescription;
currentPanel = Panels.Description;
break;
case Panels.Strings:
pnlPanel.Content = panelStrings;
currentPanel = Panels.Strings;
break;
case Panels.Versions:
pnlPanel.Content = panelVersions;
currentPanel = Panels.Versions;
break;
}
if(currentPanel == maximumPanel) btnNext.Text = "Finish";
if(currentPanel == maximumPanel)
btnNext.Text = "Finish";
lblPanelName.Visible = false;
}
@@ -297,6 +335,7 @@ namespace apprepodbmgr.Eto
{
canceled = true;
Close();
// throw new NotImplementedException();
}
@@ -308,7 +347,8 @@ namespace apprepodbmgr.Eto
// Ok...
break;
case Panels.Strings:
if(minimumPanel == Panels.Strings) return;
if(minimumPanel == Panels.Strings)
return;
pnlPanel.Content = panelDescription;
currentPanel = Panels.Description;
@@ -317,7 +357,8 @@ namespace apprepodbmgr.Eto
break;
case Panels.Versions:
if(minimumPanel == Panels.Versions) return;
if(minimumPanel == Panels.Versions)
return;
pnlPanel.Content = panelStrings;
currentPanel = Panels.Strings;
@@ -327,7 +368,8 @@ namespace apprepodbmgr.Eto
break;
}
if(currentPanel != maximumPanel) btnNext.Text = "Next";
if(currentPanel != maximumPanel)
btnNext.Text = "Next";
}
void OnBtnNextClick(object sender, EventArgs eventArgs)
@@ -337,7 +379,8 @@ namespace apprepodbmgr.Eto
switch(currentPanel)
{
case Panels.Description:
if(maximumPanel == Panels.Description) return;
if(maximumPanel == Panels.Description)
return;
pnlPanel.Content = panelStrings;
currentPanel = Panels.Strings;
@@ -346,7 +389,8 @@ namespace apprepodbmgr.Eto
break;
case Panels.Strings:
if(maximumPanel == Panels.Strings) return;
if(maximumPanel == Panels.Strings)
return;
pnlPanel.Content = panelVersions;
currentPanel = Panels.Versions;
@@ -355,7 +399,8 @@ namespace apprepodbmgr.Eto
break;
case Panels.Versions:
if(minimumPanel == Panels.Versions) return;
if(minimumPanel == Panels.Versions)
return;
pnlPanel.Content = panelStrings;
currentPanel = Panels.Strings;
@@ -365,23 +410,35 @@ namespace apprepodbmgr.Eto
break;
}
if(currentPanel == maximumPanel) btnNext.Text = "Finish";
if(currentPanel == maximumPanel)
btnNext.Text = "Finish";
return;
}
if(Context.Readmes?.Count > 0 && !string.IsNullOrWhiteSpace(panelDescription.description))
if(Context.Readmes?.Count > 0 &&
!string.IsNullOrWhiteSpace(panelDescription.description))
description = panelDescription.description;
if(!(Context.Executables?.Count > 0)) return;
if(!(Context.Executables?.Count > 0))
return;
if(!string.IsNullOrWhiteSpace(panelStrings.txtDeveloper.Text)) developer = panelStrings.txtDeveloper.Text;
if(!string.IsNullOrWhiteSpace(panelStrings.txtPublisher.Text)) publisher = panelStrings.txtPublisher.Text;
if(!string.IsNullOrWhiteSpace(panelStrings.txtProduct.Text)) product = panelStrings.txtProduct.Text;
if(!string.IsNullOrWhiteSpace(panelStrings.txtVersion.Text)) version = panelStrings.txtVersion.Text;
if(!string.IsNullOrWhiteSpace(panelStrings.txtDeveloper.Text))
developer = panelStrings.txtDeveloper.Text;
if(!string.IsNullOrWhiteSpace(panelStrings.txtPublisher.Text))
publisher = panelStrings.txtPublisher.Text;
if(!string.IsNullOrWhiteSpace(panelStrings.txtProduct.Text))
product = panelStrings.txtProduct.Text;
if(!string.IsNullOrWhiteSpace(panelStrings.txtVersion.Text))
version = panelStrings.txtVersion.Text;
foreach(object archsSelectedItem in panelVersions.treeArchs.SelectedItems)
{
if(!(archsSelectedItem is string arch)) continue;
if(!(archsSelectedItem is string arch))
continue;
if(Enum.TryParse(arch, true, out ArchitecturesTypeArchitecture realArch))
chosenArchitectures.Add(realArch);
@@ -389,12 +446,14 @@ namespace apprepodbmgr.Eto
foreach(object osesSelectedItem in panelVersions.treeOs.SelectedItems)
{
if(!(osesSelectedItem is TargetOsEntry os)) continue;
if(!(osesSelectedItem is TargetOsEntry os))
continue;
chosenOses.Add(os);
}
if(panelVersions.treeVersions.SelectedItem is string chosenVersion) version = chosenVersion;
if(panelVersions.treeVersions.SelectedItem is string chosenVersion)
version = chosenVersion;
canceled = false;
Close();
@@ -402,9 +461,7 @@ namespace apprepodbmgr.Eto
enum Panels
{
Description,
Strings,
Versions
Description, Strings, Versions
}
#region XAML UI elements

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -47,7 +47,8 @@ namespace apprepodbmgr.Eto
txtDatabase.Text = Settings.Current.DatabasePath;
txtRepository.Text = Settings.Current.RepositoryPath;
if(!string.IsNullOrWhiteSpace(txtUnar.Text)) CheckUnar();
if(!string.IsNullOrWhiteSpace(txtUnar.Text))
CheckUnar();
cmbCompAlg = new EnumDropDown<AlgoEnum>();
StackLayoutForAlgoEnum.Items.Add(new StackLayoutItem(cmbCompAlg, HorizontalAlignment.Stretch, true));
@@ -56,7 +57,9 @@ namespace apprepodbmgr.Eto
spClamdPort.Value = 3310;
chkAntivirus.Checked = Settings.Current.UseAntivirus;
frmClamd.Visible = chkAntivirus.Checked.Value;
if(Settings.Current.UseAntivirus && Settings.Current.UseClamd)
if(Settings.Current.UseAntivirus &&
Settings.Current.UseClamd)
{
chkClamd.Checked = Settings.Current.UseClamd;
txtClamdHost.Text = Settings.Current.ClamdHost;
@@ -64,7 +67,9 @@ namespace apprepodbmgr.Eto
chkClamdIsLocal.Checked = Settings.Current.ClamdIsLocal;
}
if(!Settings.Current.UseAntivirus || !Settings.Current.UseVirusTotal) return;
if(!Settings.Current.UseAntivirus ||
!Settings.Current.UseVirusTotal)
return;
chkVirusTotal.Checked = true;
chkVirusTotal.Enabled = true;
@@ -73,10 +78,7 @@ namespace apprepodbmgr.Eto
btnVirusTotal.Enabled = true;
}
protected void OnBtnCancelClicked(object sender, EventArgs e)
{
Close();
}
protected void OnBtnCancelClicked(object sender, EventArgs e) => Close();
protected void OnBtnApplyClicked(object sender, EventArgs e)
{
@@ -86,7 +88,9 @@ namespace apprepodbmgr.Eto
Settings.Current.DatabasePath = txtDatabase.Text;
Settings.Current.RepositoryPath = txtRepository.Text;
Settings.Current.CompressionAlgorithm = cmbCompAlg.SelectedValue;
if(!chkClamd.Checked.Value || !chkAntivirus.Checked.Value)
if(!chkClamd.Checked.Value ||
!chkAntivirus.Checked.Value)
{
Settings.Current.UseClamd = false;
Settings.Current.ClamdHost = null;
@@ -94,7 +98,8 @@ namespace apprepodbmgr.Eto
Settings.Current.ClamdIsLocal = false;
}
if(chkVirusTotal.Checked.Value && chkAntivirus.Checked.Value)
if(chkVirusTotal.Checked.Value &&
chkAntivirus.Checked.Value)
{
Settings.Current.UseVirusTotal = true;
Settings.Current.VirusTotalKey = txtVirusTotal.Text;
@@ -117,11 +122,17 @@ namespace apprepodbmgr.Eto
protected void OnBtnUnarClicked(object sender, EventArgs e)
{
OpenFileDialog dlgFile = new OpenFileDialog {Title = "Choose UnArchiver executable", MultiSelect = false};
var dlgFile = new OpenFileDialog
{
Title = "Choose UnArchiver executable",
MultiSelect = false
};
if(!string.IsNullOrWhiteSpace(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)))
dlgFile.Directory = new Uri(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles));
if(dlgFile.ShowDialog(this) != DialogResult.Ok) return;
if(dlgFile.ShowDialog(this) != DialogResult.Ok)
return;
txtUnar.Text = dlgFile.FileName;
lblUnarVersion.Visible = false;
@@ -130,23 +141,31 @@ namespace apprepodbmgr.Eto
protected void OnBtnTmpClicked(object sender, EventArgs e)
{
SelectFolderDialog dlgFolder =
new SelectFolderDialog {Title = "Choose temporary folder", Directory = Path.GetTempPath()};
var dlgFolder = new SelectFolderDialog
{
Title = "Choose temporary folder",
Directory = Path.GetTempPath()
};
if(dlgFolder.ShowDialog(this) == DialogResult.Ok) txtTmp.Text = dlgFolder.Directory;
if(dlgFolder.ShowDialog(this) == DialogResult.Ok)
txtTmp.Text = dlgFolder.Directory;
}
protected void OnBtnRepositoryClicked(object sender, EventArgs e)
{
SelectFolderDialog dlgFolder =
new SelectFolderDialog {Title = "Choose repository folder", Directory = Path.GetTempPath()};
var dlgFolder = new SelectFolderDialog
{
Title = "Choose repository folder",
Directory = Path.GetTempPath()
};
if(dlgFolder.ShowDialog(this) == DialogResult.Ok) txtRepository.Text = dlgFolder.Directory;
if(dlgFolder.ShowDialog(this) == DialogResult.Ok)
txtRepository.Text = dlgFolder.Directory;
}
protected void OnBtnDatabaseClicked(object sender, EventArgs e)
{
SaveFileDialog dlgFile = new SaveFileDialog
var dlgFile = new SaveFileDialog
{
Title = "Choose database to open/create",
Directory = new Uri(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)),
@@ -154,20 +173,28 @@ namespace apprepodbmgr.Eto
FileName = "apprepodbmgr.db"
};
if(dlgFile.ShowDialog(this) != DialogResult.Ok) return;
if(dlgFile.ShowDialog(this) != DialogResult.Ok)
return;
if(File.Exists(dlgFile.FileName))
{
DbCore dbCore = new SQLite();
bool notDb = false;
try { notDb |= !dbCore.OpenDb(dlgFile.FileName, null, null, null); }
catch { notDb = true; }
try
{
notDb |= !dbCore.OpenDb(dlgFile.FileName, null, null, null);
}
catch
{
notDb = true;
}
if(notDb)
{
MessageBox.Show("Cannot open specified file as a database, please choose another.",
MessageBoxType.Error);
return;
}
@@ -178,13 +205,20 @@ namespace apprepodbmgr.Eto
DbCore dbCore = new SQLite();
bool notDb = false;
try { notDb |= !dbCore.CreateDb(dlgFile.FileName, null, null, null); }
catch { notDb = true; }
try
{
notDb |= !dbCore.CreateDb(dlgFile.FileName, null, null, null);
}
catch
{
notDb = true;
}
if(notDb)
{
MessageBox.Show("Cannot create a database in the specified file as a database.",
MessageBoxType.Error);
return;
}
@@ -201,35 +235,29 @@ namespace apprepodbmgr.Eto
oldUnarPath = Settings.Current.UnArchiverPath;
Settings.Current.UnArchiverPath = txtUnar.Text;
Thread thdCheckUnar = new Thread(Workers.CheckUnar);
var thdCheckUnar = new Thread(Workers.CheckUnar);
thdCheckUnar.Start();
}
void CheckUnarFinished(string text)
void CheckUnarFinished(string text) => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{
Workers.FinishedWithText -= CheckUnarFinished;
Workers.Failed -= CheckUnarFailed;
Workers.FinishedWithText -= CheckUnarFinished;
Workers.Failed -= CheckUnarFailed;
lblUnarVersion.Text = text;
lblUnarVersion.Visible = true;
Settings.Current.UnArchiverPath = oldUnarPath;
});
}
lblUnarVersion.Text = text;
lblUnarVersion.Visible = true;
Settings.Current.UnArchiverPath = oldUnarPath;
});
void CheckUnarFailed(string text)
void CheckUnarFailed(string text) => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{
Workers.FinishedWithText -= CheckUnarFinished;
Workers.Failed -= CheckUnarFailed;
Workers.FinishedWithText -= CheckUnarFinished;
Workers.Failed -= CheckUnarFailed;
txtUnar.Text = string.IsNullOrWhiteSpace(oldUnarPath) ? "" : oldUnarPath;
Settings.Current.UnArchiverPath = oldUnarPath;
MessageBox.Show(text, MessageBoxType.Error);
});
}
txtUnar.Text = string.IsNullOrWhiteSpace(oldUnarPath) ? "" : oldUnarPath;
Settings.Current.UnArchiverPath = oldUnarPath;
MessageBox.Show(text, MessageBoxType.Error);
});
protected void OnChkAntivirusToggled(object sender, EventArgs e)
{
@@ -253,14 +281,15 @@ namespace apprepodbmgr.Eto
if(string.IsNullOrEmpty(txtClamdHost.Text))
{
MessageBox.Show("clamd host cannot be empty", MessageBoxType.Error);
return;
}
string oldVersion = Context.ClamdVersion;
string oldVersion = Context.ClamdVersion;
Context.ClamdVersion = null;
string oldHost = Settings.Current.ClamdHost;
ushort oldPort = Settings.Current.ClamdPort;
string oldHost = Settings.Current.ClamdHost;
ushort oldPort = Settings.Current.ClamdPort;
Settings.Current.ClamdHost = txtClamdHost.Text;
Settings.Current.ClamdPort = (ushort)spClamdPort.Value;
@@ -272,6 +301,7 @@ namespace apprepodbmgr.Eto
if(string.IsNullOrEmpty(Context.ClamdVersion))
{
MessageBox.Show("Cannot connect to clamd", MessageBoxType.Error);
return;
}
@@ -290,39 +320,38 @@ namespace apprepodbmgr.Eto
protected void OnBtnVirusTotalClicked(object sender, EventArgs e)
{
Workers.Failed += VirusTotalTestFailed;
if(!Workers.TestVirusTotal(txtVirusTotal.Text)) return;
if(!Workers.TestVirusTotal(txtVirusTotal.Text))
return;
lblVirusTotal.Visible = true;
lblVirusTotal.Text = "Working!";
}
static void VirusTotalTestFailed(string text)
{
MessageBox.Show(text, MessageBoxType.Error);
}
static void VirusTotalTestFailed(string text) => MessageBox.Show(text, MessageBoxType.Error);
#region XAML UI elements
#pragma warning disable 0649
TextBox txtTmp;
TextBox txtUnar;
TextBox txtDatabase;
TextBox txtRepository;
Label lblUnarVersion;
EnumDropDown<AlgoEnum> cmbCompAlg;
StackLayout StackLayoutForAlgoEnum;
GroupBox frmClamd;
CheckBox chkAntivirus;
CheckBox chkClamd;
TextBox txtClamdHost;
NumericUpDown spClamdPort;
Button btnClamdTest;
Label lblClamdVersion;
CheckBox chkClamdIsLocal;
GroupBox frmVirusTotal;
CheckBox chkVirusTotal;
TextBox txtVirusTotal;
Button btnVirusTotal;
Label lblVirusTotal;
TextBox txtTmp;
TextBox txtUnar;
TextBox txtDatabase;
TextBox txtRepository;
Label lblUnarVersion;
readonly EnumDropDown<AlgoEnum> cmbCompAlg;
StackLayout StackLayoutForAlgoEnum;
GroupBox frmClamd;
CheckBox chkAntivirus;
CheckBox chkClamd;
TextBox txtClamdHost;
NumericUpDown spClamdPort;
Button btnClamdTest;
Label lblClamdVersion;
CheckBox chkClamdIsLocal;
GroupBox frmVirusTotal;
CheckBox chkVirusTotal;
TextBox txtVirusTotal;
Button btnVirusTotal;
Label lblVirusTotal;
#pragma warning restore 0649
#endregion XAML UI elements
}

File diff suppressed because it is too large Load Diff

View File

@@ -11,9 +11,9 @@ namespace apprepodbmgr.Eto
{
public class pnlDescription : Panel
{
ObservableCollection<ListItem> cmbCodepagesItems;
Encoding currentEncoding;
public string description;
readonly ObservableCollection<ListItem> cmbCodepagesItems;
Encoding currentEncoding;
public string description;
public pnlDescription()
{
@@ -21,31 +21,52 @@ namespace apprepodbmgr.Eto
treeFiles.Columns.Add(new GridColumn
{
DataCell = new TextBoxCell {Binding = Binding.Property<string, string>(r => r)},
DataCell = new TextBoxCell
{
Binding = Binding.Property<string, string>(r => r)
},
HeaderText = "File"
});
treeFiles.AllowMultipleSelection = false;
treeFiles.SelectionChanged += TreeFilesOnSelectionChanged;
cmbCodepagesItems = new ObservableCollection<ListItem>();
foreach(EncodingInfo enc in Claunia.Encoding.Encoding.GetEncodings())
cmbCodepagesItems.Add(new ListItem {Key = enc.Name, Text = enc.DisplayName});
cmbCodepagesItems.Add(new ListItem
{
Key = enc.Name,
Text = enc.DisplayName
});
foreach(System.Text.EncodingInfo enc in Encoding.GetEncodings())
cmbCodepagesItems.Add(new ListItem {Key = enc.Name, Text = enc.GetEncoding().EncodingName});
cmbCodepagesItems.Add(new ListItem
{
Key = enc.Name,
Text = enc.GetEncoding().EncodingName
});
cmbCodepages.DataStore = cmbCodepagesItems.OrderBy(t => t.Text);
try
{
currentEncoding = Claunia.Encoding.Encoding.GetEncoding("ibm437");
cmbCodepages.SelectedKey = currentEncoding.BodyName;
}
catch { currentEncoding = Encoding.ASCII; }
catch
{
currentEncoding = Encoding.ASCII;
}
cmbCodepages.SelectedIndexChanged += CmbCodepagesOnSelectedIndexChanged;
}
void CmbCodepagesOnSelectedIndexChanged(object sender, EventArgs eventArgs)
{
try { currentEncoding = Claunia.Encoding.Encoding.GetEncoding(cmbCodepages.SelectedKey); }
try
{
currentEncoding = Claunia.Encoding.Encoding.GetEncoding(cmbCodepages.SelectedKey);
}
catch
{
currentEncoding = Encoding.ASCII;
@@ -59,9 +80,11 @@ namespace apprepodbmgr.Eto
{
txtDescription.Text = "";
description = null;
if(!(treeFiles.SelectedItem is string file)) return;
StreamReader sr = new StreamReader(file, currentEncoding);
if(!(treeFiles.SelectedItem is string file))
return;
var sr = new StreamReader(file, currentEncoding);
description = sr.ReadToEnd();
txtDescription.Text = description;
sr.Close();

View File

@@ -12,9 +12,13 @@ namespace apprepodbmgr.Eto
treeStrings.AllowMultipleSelection = false;
treeStrings.ShowHeader = false;
treeStrings.Columns.Add(new GridColumn
{
DataCell = new TextBoxCell {Binding = Binding.Property<string, string>(r => r)},
DataCell = new TextBoxCell
{
Binding = Binding.Property<string, string>(r => r)
},
HeaderText = "String"
});
}
@@ -22,7 +26,9 @@ namespace apprepodbmgr.Eto
void OnBtnDeveloperClick(object sender, EventArgs eventArgs)
{
txtDeveloper.Text = "";
if(!(treeStrings.SelectedItem is string str)) return;
if(!(treeStrings.SelectedItem is string str))
return;
txtDeveloper.Text = str;
}
@@ -30,7 +36,9 @@ namespace apprepodbmgr.Eto
void OnBtnPublisherClick(object sender, EventArgs eventArgs)
{
txtPublisher.Text = "";
if(!(treeStrings.SelectedItem is string str)) return;
if(!(treeStrings.SelectedItem is string str))
return;
txtPublisher.Text = str;
}
@@ -38,7 +46,9 @@ namespace apprepodbmgr.Eto
void OnBtnProductClick(object sender, EventArgs eventArgs)
{
txtProduct.Text = "";
if(!(treeStrings.SelectedItem is string str)) return;
if(!(treeStrings.SelectedItem is string str))
return;
txtProduct.Text = str;
}
@@ -46,7 +56,9 @@ namespace apprepodbmgr.Eto
void OnBtnVersionClick(object sender, EventArgs eventArgs)
{
txtVersion.Text = "";
if(!(treeStrings.SelectedItem is string str)) return;
if(!(treeStrings.SelectedItem is string str))
return;
txtVersion.Text = str;
}

View File

@@ -19,22 +19,37 @@ namespace apprepodbmgr.Eto
treeArchs.Columns.Add(new GridColumn
{
DataCell = new TextBoxCell {Binding = Binding.Property<string, string>(r => r)},
DataCell = new TextBoxCell
{
Binding = Binding.Property<string, string>(r => r)
},
HeaderText = "Arch"
});
treeOs.Columns.Add(new GridColumn
{
DataCell = new TextBoxCell {Binding = Binding.Property<TargetOsEntry, string>(r => r.name)},
DataCell = new TextBoxCell
{
Binding = Binding.Property<TargetOsEntry, string>(r => r.name)
},
HeaderText = "Name"
});
treeOs.Columns.Add(new GridColumn
{
DataCell = new TextBoxCell {Binding = Binding.Property<TargetOsEntry, string>(r => r.version)},
DataCell = new TextBoxCell
{
Binding = Binding.Property<TargetOsEntry, string>(r => r.version)
},
HeaderText = "Version"
});
treeVersions.Columns.Add(new GridColumn
{
DataCell = new TextBoxCell {Binding = Binding.Property<string, string>(r => r)},
DataCell = new TextBoxCell
{
Binding = Binding.Property<string, string>(r => r)
},
HeaderText = "Version"
});
}