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 public enum AlgoEnum
{ {
GZip, GZip, BZip2, LZMA,
BZip2,
LZMA,
LZip LZip
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

@@ -51,11 +51,14 @@ namespace DiscImageChef.Interop
public static PlatformID GetRealPlatformID() 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; return (PlatformID)(int)Environment.OSVersion.Platform;
int error = uname(out utsname unixname); 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) switch(unixname.sysname)
{ {
@@ -72,6 +75,7 @@ namespace DiscImageChef.Interop
{ {
IntPtr pLen = Marshal.AllocHGlobal(sizeof(int)); IntPtr pLen = Marshal.AllocHGlobal(sizeof(int));
int osx_error = OSX_sysctlbyname("hw.machine", IntPtr.Zero, pLen, IntPtr.Zero, 0); int osx_error = OSX_sysctlbyname("hw.machine", IntPtr.Zero, pLen, IntPtr.Zero, 0);
if(osx_error != 0) if(osx_error != 0)
{ {
Marshal.FreeHGlobal(pLen); Marshal.FreeHGlobal(pLen);
@@ -82,6 +86,7 @@ namespace DiscImageChef.Interop
int length = Marshal.ReadInt32(pLen); int length = Marshal.ReadInt32(pLen);
IntPtr pStr = Marshal.AllocHGlobal(length); 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) if(osx_error != 0)
{ {
Marshal.FreeHGlobal(pStr); Marshal.FreeHGlobal(pStr);
@@ -97,7 +102,8 @@ namespace DiscImageChef.Interop
if(machine.StartsWith("iPad", StringComparison.Ordinal) || if(machine.StartsWith("iPad", StringComparison.Ordinal) ||
machine.StartsWith("iPod", StringComparison.Ordinal) || machine.StartsWith("iPod", StringComparison.Ordinal) ||
machine.StartsWith("iPhone", StringComparison.Ordinal)) return PlatformID.iOS; machine.StartsWith("iPhone", StringComparison.Ordinal))
return PlatformID.iOS;
return PlatformID.MacOSX; return PlatformID.MacOSX;
} }
@@ -129,60 +135,39 @@ namespace DiscImageChef.Interop
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("MINGW32_NT", StringComparison.Ordinal) ||
unixname.sysname.StartsWith("MSYS_NT", StringComparison.Ordinal) || unixname.sysname.StartsWith("MSYS_NT", StringComparison.Ordinal) ||
unixname.sysname.StartsWith("UWIN", StringComparison.Ordinal)) return PlatformID.Win32NT; unixname.sysname.StartsWith("UWIN", StringComparison.Ordinal))
return PlatformID.Win32NT;
return PlatformID.Unknown; return PlatformID.Unknown;
} }
} }
} }
/// <summary> /// <summary>Checks if the underlying runtime runs in 64-bit mode</summary>
/// Checks if the underlying runtime runs in 64-bit mode public static bool Is64Bit() => IntPtr.Size == 8;
/// </summary>
public static bool Is64Bit()
{
return IntPtr.Size == 8;
}
/// <summary> /// <summary>Checks if the underlying runtime runs in 32-bit mode</summary>
/// Checks if the underlying runtime runs in 32-bit mode public static bool Is32Bit() => IntPtr.Size == 4;
/// </summary>
public static bool Is32Bit()
{
return IntPtr.Size == 4;
}
/// <summary> /// <summary>POSIX uname structure, size from OSX, big enough to handle extra fields</summary>
/// POSIX uname structure, size from OSX, big enough to handle extra fields
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
struct utsname struct utsname
{ {
/// <summary> /// <summary>System name</summary>
/// System name
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string sysname; public readonly string sysname;
/// <summary> /// <summary>Node name</summary>
/// Node name
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string nodename; public readonly string nodename;
/// <summary> /// <summary>Release level</summary>
/// Release level
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string release; public readonly string release;
/// <summary> /// <summary>Version level</summary>
/// Version level
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string version; public readonly string version;
/// <summary> /// <summary>Hardware level</summary>
/// Hardware level
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] [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 class IO
{ {
public static List<string> EnumerateFiles(string path, string searchPattern, public static List<string> EnumerateFiles(string path, string searchPattern, SearchOption searchOption,
SearchOption searchOption,
bool followLinks = true, bool symlinks = true) 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> files = new List<string>();
List<string> directories = new List<string>(); List<string> directories = new List<string>();
foreach(string file in Directory.EnumerateFiles(path, searchPattern)) foreach(string file in Directory.EnumerateFiles(path, searchPattern))
{ {
FileInfo fi = new FileInfo(file); var fi = new FileInfo(file);
if(fi.Attributes.HasFlag(FileAttributes.ReparsePoint) && symlinks) files.Add(file);
if(fi.Attributes.HasFlag(FileAttributes.ReparsePoint) && symlinks)
files.Add(file);
else if(!fi.Attributes.HasFlag(FileAttributes.ReparsePoint)) else if(!fi.Attributes.HasFlag(FileAttributes.ReparsePoint))
files.Add(file); files.Add(file);
} }
if(searchOption != SearchOption.AllDirectories) return files; if(searchOption != SearchOption.AllDirectories)
return files;
foreach(string directory in Directory.EnumerateDirectories(path, searchPattern)) foreach(string directory in Directory.EnumerateDirectories(path, searchPattern))
{ {
DirectoryInfo di = new DirectoryInfo(directory); var di = new DirectoryInfo(directory);
if(!di.Attributes.HasFlag(FileAttributes.ReparsePoint)) if(!di.Attributes.HasFlag(FileAttributes.ReparsePoint))
files.AddRange(EnumerateFiles(directory, searchPattern, searchOption, followLinks, symlinks)); files.AddRange(EnumerateFiles(directory, searchPattern, searchOption, followLinks, symlinks));
} }
@@ -35,20 +39,20 @@ namespace apprepodbmgr.Core
return files; return files;
} }
public static List<string> EnumerateDirectories(string path, string searchPattern, public static List<string> EnumerateDirectories(string path, string searchPattern, SearchOption searchOption,
SearchOption searchOption,
bool followLinks = true, bool symlinks = true) 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>(); 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) directories.AddRange(from directory in Directory.EnumerateDirectories(path, searchPattern) let di =
let di = new DirectoryInfo(directory) new DirectoryInfo(directory)
where !di.Attributes.HasFlag(FileAttributes.ReparsePoint) where !di.Attributes.HasFlag(FileAttributes.ReparsePoint) select directory);
select directory);
List<string> newDirectories = new List<string>(); List<string> newDirectories = new List<string>();
@@ -65,17 +69,18 @@ namespace apprepodbmgr.Core
{ {
List<string> directories = new List<string>(); List<string> directories = new List<string>();
List<string> links = (from file in Directory.EnumerateFiles(path, searchPattern) List<string> links = (from file in Directory.EnumerateFiles(path, searchPattern) let fi = new FileInfo(file)
let fi = new FileInfo(file) where fi.Attributes.HasFlag(FileAttributes.ReparsePoint) select file).ToList();
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)) foreach(string directory in Directory.EnumerateDirectories(path, searchPattern))
{ {
DirectoryInfo di = new DirectoryInfo(directory); var di = new DirectoryInfo(directory);
if(!di.Attributes.HasFlag(FileAttributes.ReparsePoint)) directories.Add(directory);
if(!di.Attributes.HasFlag(FileAttributes.ReparsePoint))
directories.Add(directory);
else //if (!links.Contains(directory)) else //if (!links.Contains(directory))
links.Add(directory); links.Add(directory);
} }

View File

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

View File

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

View File

@@ -49,16 +49,23 @@ namespace apprepodbmgr.Core
SQLiteCommand dbcmd = dbCon.CreateCommand(); SQLiteCommand dbcmd = dbCon.CreateCommand();
dbcmd.CommandText = SQL; dbcmd.CommandText = SQL;
SQLiteDataAdapter dAdapter = new SQLiteDataAdapter {SelectCommand = dbcmd};
DataSet dSet = new DataSet(); var dAdapter = new SQLiteDataAdapter
{
SelectCommand = dbcmd
};
var dSet = new DataSet();
dAdapter.Fill(dSet); dAdapter.Fill(dSet);
DataTable dTable = dSet.Tables[0]; 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) if((long)dTable.Rows[0]["version"] != 1)
{ {
dbCon = null; dbCon = null;
return false; return false;
} }
@@ -71,6 +78,7 @@ namespace apprepodbmgr.Core
Console.WriteLine("Error opening DB."); Console.WriteLine("Error opening DB.");
Console.WriteLine(ex.Message); Console.WriteLine(ex.Message);
dbCon = null; dbCon = null;
return false; return false;
} }
} }
@@ -99,8 +107,7 @@ namespace apprepodbmgr.Core
dbCmd.CommandText = sql; dbCmd.CommandText = sql;
dbCmd.ExecuteNonQuery(); dbCmd.ExecuteNonQuery();
sql = sql = "INSERT INTO apprepodbmgr ( version, name ) VALUES ( '1', 'Canary Islands Computer Museum' )";
"INSERT INTO apprepodbmgr ( version, name ) VALUES ( '1', 'Canary Islands Computer Museum' )";
dbCmd.CommandText = sql; dbCmd.CommandText = sql;
dbCmd.ExecuteNonQuery(); dbCmd.ExecuteNonQuery();
@@ -118,6 +125,7 @@ namespace apprepodbmgr.Core
dbCmd.Dispose(); dbCmd.Dispose();
dbCon = null; dbCon = null;
return true; return true;
} }
catch(SQLiteException ex) catch(SQLiteException ex)
@@ -125,14 +133,12 @@ namespace apprepodbmgr.Core
Console.WriteLine("Error opening DB."); Console.WriteLine("Error opening DB.");
Console.WriteLine(ex.Message); Console.WriteLine(ex.Message);
dbCon = null; dbCon = null;
return false; return false;
} }
} }
public override IDbDataAdapter GetNewDataAdapter() public override IDbDataAdapter GetNewDataAdapter() => new SQLiteDataAdapter();
{
return new SQLiteDataAdapter();
}
public override long LastInsertRowId => dbCon.LastInsertRowId; public override long LastInsertRowId => dbCon.LastInsertRowId;
#endregion #endregion

View File

@@ -36,12 +36,9 @@ namespace apprepodbmgr.Core
"DROP TABLE IF EXISTS `files` ;\n\n" + "DROP TABLE IF EXISTS `files` ;\n\n" +
"CREATE TABLE IF NOT EXISTS `files` (\n" + "CREATE TABLE IF NOT EXISTS `files` (\n" +
" `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" + " `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" `sha256` VARCHAR(64) NOT NULL,\n" + " `sha256` VARCHAR(64) NOT NULL,\n" + " `crack` BOOLEAN NOT NULL,\n" +
" `crack` BOOLEAN NOT NULL,\n" + " `hasvirus` BOOLEAN NULL,\n" + " `clamtime` DATETIME NULL,\n" +
" `hasvirus` BOOLEAN NULL,\n" + " `vtotaltime` DATETIME NULL,\n" + " `virus` VARCHAR(128) NULL,\n" +
" `clamtime` DATETIME NULL,\n" +
" `vtotaltime` DATETIME NULL,\n" +
" `virus` VARCHAR(128) NULL,\n" +
" `length` BIGINT NOT NULL);\n\n" + " `length` BIGINT NOT NULL);\n\n" +
"CREATE UNIQUE INDEX `files_id_UNIQUE` ON `files` (`id` ASC);\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 UNIQUE INDEX `files_sha256_UNIQUE` ON `files` (`sha256` ASC);\n\n" +
@@ -55,23 +52,15 @@ namespace apprepodbmgr.Core
"DROP TABLE IF EXISTS `apps` ;\n\n" + "DROP TABLE IF EXISTS `apps` ;\n\n" +
"CREATE TABLE IF NOT EXISTS `apps` (\n" + "CREATE TABLE IF NOT EXISTS `apps` (\n" +
" `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" + " `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" `mdid` CHAR(40) NOT NULL,\n" + " `mdid` CHAR(40) NOT NULL,\n" + " `developer` VARCHAR(45) NOT NULL,\n" +
" `developer` VARCHAR(45) NOT NULL,\n" + " `product` VARCHAR(45) NOT NULL,\n" + " `version` VARCHAR(45) NULL,\n" +
" `product` VARCHAR(45) NOT NULL,\n" +
" `version` VARCHAR(45) NULL,\n" +
" `languages` VARCHAR(45) NULL,\n" + " `languages` VARCHAR(45) NULL,\n" +
" `architecture` VARCHAR(45) NULL,\n" + " `architecture` VARCHAR(45) NULL,\n" + " `targetos` VARCHAR(45) NULL,\n" +
" `targetos` VARCHAR(45) NULL,\n" + " `format` VARCHAR(45) NULL,\n" + " `description` TEXT NULL,\n" +
" `format` VARCHAR(45) NULL,\n" + " `oem` BOOLEAN NOT NULL,\n" + " `upgrade` BOOLEAN NOT NULL,\n" +
" `description` TEXT NULL,\n" + " `update` BOOLEAN NOT NULL,\n" + " `source` BOOLEAN NOT NULL,\n" +
" `oem` BOOLEAN NOT NULL,\n" + " `files` BOOLEAN NOT NULL,\n" + " `installer` BOOLEAN NOT NULL,\n" +
" `upgrade` BOOLEAN NOT NULL,\n" + " `xml` BLOB NULL,\n" + " `json` BLOB 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" + " `icon` BLOB NULL);\n\n" +
"CREATE UNIQUE INDEX `apps_id_UNIQUE` ON `apps` (`id` ASC);\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 UNIQUE INDEX `apps_mdid_UNIQUE` ON `apps` (`mdid` ASC);\n\n" +

View File

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

View File

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

View File

@@ -46,27 +46,26 @@ namespace apprepodbmgr.Core
public static void InitClamd() public static void InitClamd()
{ {
if(!Settings.Current.UseClamd || !Settings.Current.UseAntivirus) if(!Settings.Current.UseClamd ||
!Settings.Current.UseAntivirus)
{ {
Context.ClamdVersion = null; Context.ClamdVersion = null;
return; return;
} }
TestClamd(); 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); clam = new ClamClient(Settings.Current.ClamdHost, Settings.Current.ClamdPort);
Context.ClamdVersion = await clam.GetVersionAsync(); Context.ClamdVersion = await clam.GetVersionAsync();
} }
catch(SocketException) { } catch(SocketException) {}
}).Wait(); }).Wait();
}
public static void ClamScanFileFromRepo(DbFile file) public static void ClamScanFileFromRepo(DbFile file)
{ {
@@ -75,10 +74,12 @@ namespace apprepodbmgr.Core
if(Context.ClamdVersion == null) if(Context.ClamdVersion == null)
{ {
Failed?.Invoke("clamd is not usable"); Failed?.Invoke("clamd is not usable");
return; return;
} }
if(clam == null) Failed?.Invoke("clamd is not initalized"); if(clam == null)
Failed?.Invoke("clamd is not initalized");
string repoPath; string repoPath;
AlgoEnum algorithm; AlgoEnum algorithm;
@@ -90,6 +91,7 @@ namespace apprepodbmgr.Core
repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[1].ToString(), file.Sha256[2].ToString(),
file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".gz"); file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".gz");
algorithm = AlgoEnum.GZip; algorithm = AlgoEnum.GZip;
} }
else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), 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(), repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[1].ToString(), file.Sha256[2].ToString(),
file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".bz2"); file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".bz2");
algorithm = AlgoEnum.BZip2; algorithm = AlgoEnum.BZip2;
} }
else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), 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[1].ToString(), file.Sha256[2].ToString(),
file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256[3].ToString(), file.Sha256[4].ToString(),
file.Sha256 + ".lzma"); file.Sha256 + ".lzma");
algorithm = AlgoEnum.LZMA; algorithm = AlgoEnum.LZMA;
} }
else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), 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(), repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[1].ToString(), file.Sha256[2].ToString(),
file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".lz"); file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".lz");
algorithm = AlgoEnum.LZip; algorithm = AlgoEnum.LZip;
} }
else else
{ {
Failed?.Invoke($"Cannot find file with hash {file.Sha256} in the repository"); Failed?.Invoke($"Cannot find file with hash {file.Sha256} in the repository");
return; return;
} }
@@ -133,11 +139,12 @@ namespace apprepodbmgr.Core
Stream zStream = null; Stream zStream = null;
if(Settings.Current.ClamdIsLocal) 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()); string tmpFile = Path.Combine(Settings.Current.TemporaryFolder, Path.GetTempFileName());
FileStream outFs = new FileStream(tmpFile, FileMode.Create, FileAccess.Write); var outFs = new FileStream(tmpFile, FileMode.Create, FileAccess.Write);
FileStream inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read); var inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read);
if(algorithm == AlgoEnum.LZMA) if(algorithm == AlgoEnum.LZMA)
{ {
@@ -146,7 +153,8 @@ namespace apprepodbmgr.Core
inFs.Seek(8, SeekOrigin.Current); inFs.Seek(8, SeekOrigin.Current);
zStream = new LzmaStream(properties, inFs, inFs.Length - 13, file.Length); 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); UpdateProgress?.Invoke("Uncompressing file...", null, 0, 0);
@@ -158,6 +166,7 @@ namespace apprepodbmgr.Core
outFs.Close(); outFs.Close();
#if DEBUG #if DEBUG
stopwatch.Stop(); stopwatch.Stop();
Console.WriteLine("Core.ClamScanFileFromRepo({0}): Uncompressing took {1} seconds", file, Console.WriteLine("Core.ClamScanFileFromRepo({0}): Uncompressing took {1} seconds", file,
stopwatch.Elapsed.TotalSeconds); stopwatch.Elapsed.TotalSeconds);
#endif #endif
@@ -167,10 +176,13 @@ namespace apprepodbmgr.Core
#if DEBUG #if DEBUG
stopwatch.Restart(); stopwatch.Restart();
#endif #endif
Task.Run(async () => { result = await clam.ScanFileOnServerMultithreadedAsync(tmpFile); }) Task.Run(async () =>
.Wait(); {
result = await clam.ScanFileOnServerMultithreadedAsync(tmpFile);
}).Wait();
#if DEBUG #if DEBUG
stopwatch.Stop(); stopwatch.Stop();
Console.WriteLine("Core.ClamScanFileFromRepo({0}): Clamd took {1} seconds to scan", file, Console.WriteLine("Core.ClamScanFileFromRepo({0}): Clamd took {1} seconds to scan", file,
stopwatch.Elapsed.TotalSeconds); stopwatch.Elapsed.TotalSeconds);
#endif #endif
@@ -184,34 +196,41 @@ namespace apprepodbmgr.Core
#if DEBUG #if DEBUG
stopwatch.Restart(); stopwatch.Restart();
#endif #endif
Task.Run(async () => { result = await clam.ScanFileOnServerMultithreadedAsync(repoPath); }) Task.Run(async () =>
.Wait(); {
result = await clam.ScanFileOnServerMultithreadedAsync(repoPath);
}).Wait();
#if DEBUG #if DEBUG
stopwatch.Stop(); stopwatch.Stop();
Console.WriteLine("Core.ClamScanFileFromRepo({0}): Clamd took {1} seconds to scan", file, Console.WriteLine("Core.ClamScanFileFromRepo({0}): Clamd took {1} seconds to scan", file,
stopwatch.Elapsed.TotalSeconds); stopwatch.Elapsed.TotalSeconds);
#endif #endif
} }
else else
{ {
FileStream inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read); var inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read);
switch(algorithm) switch(algorithm)
{ {
case AlgoEnum.GZip: case AlgoEnum.GZip:
zStream = new GZipStream(inFs, CompressionMode.Decompress); zStream = new GZipStream(inFs, CompressionMode.Decompress);
break; break;
case AlgoEnum.BZip2: case AlgoEnum.BZip2:
zStream = new BZip2Stream(inFs, CompressionMode.Decompress); zStream = new BZip2Stream(inFs, CompressionMode.Decompress);
break; break;
case AlgoEnum.LZMA: case AlgoEnum.LZMA:
byte[] properties = new byte[5]; byte[] properties = new byte[5];
inFs.Read(properties, 0, 5); inFs.Read(properties, 0, 5);
inFs.Seek(8, SeekOrigin.Current); inFs.Seek(8, SeekOrigin.Current);
zStream = new LzmaStream(properties, inFs, inFs.Length - 13, file.Length); zStream = new LzmaStream(properties, inFs, inFs.Length - 13, file.Length);
break; break;
case AlgoEnum.LZip: case AlgoEnum.LZip:
zStream = new LZipStream(inFs, CompressionMode.Decompress); zStream = new LZipStream(inFs, CompressionMode.Decompress);
break; break;
} }
@@ -220,16 +239,21 @@ namespace apprepodbmgr.Core
#if DEBUG #if DEBUG
stopwatch.Restart(); stopwatch.Restart();
#endif #endif
Task.Run(async () => { result = await clam.SendAndScanFileAsync(zStream); }).Wait(); Task.Run(async () =>
{
result = await clam.SendAndScanFileAsync(zStream);
}).Wait();
#if DEBUG #if DEBUG
stopwatch.Stop(); stopwatch.Stop();
Console.WriteLine("Core.ClamScanFileFromRepo({0}): Clamd took {1} seconds to scan", file, Console.WriteLine("Core.ClamScanFileFromRepo({0}): Clamd took {1} seconds to scan", file,
stopwatch.Elapsed.TotalSeconds); stopwatch.Elapsed.TotalSeconds);
#endif #endif
zStream.Close(); zStream.Close();
} }
if(result.InfectedFiles != null && result.InfectedFiles.Count > 0) if(result.InfectedFiles != null &&
result.InfectedFiles.Count > 0)
{ {
file.HasVirus = true; file.HasVirus = true;
file.Virus = result.InfectedFiles[0].VirusName; file.Virus = result.InfectedFiles[0].VirusName;
@@ -248,7 +272,7 @@ namespace apprepodbmgr.Core
ScanFinished?.Invoke(file); ScanFinished?.Invoke(file);
} }
catch(ThreadAbortException) { } catch(ThreadAbortException) {}
catch(Exception ex) catch(Exception ex)
{ {
Failed?.Invoke($"Exception {ex.Message} when calling clamd"); Failed?.Invoke($"Exception {ex.Message} when calling clamd");
@@ -270,11 +294,14 @@ namespace apprepodbmgr.Core
Failed?.Invoke("Could not get files from database."); Failed?.Invoke("Could not get files from database.");
#if DEBUG #if DEBUG
stopwatch.Stop(); stopwatch.Stop();
Console.WriteLine("Core.ClamScanAllFiles(): Took {0} seconds to get files from database", Console.WriteLine("Core.ClamScanAllFiles(): Took {0} seconds to get files from database",
stopwatch.Elapsed.TotalSeconds); stopwatch.Elapsed.TotalSeconds);
stopwatch.Restart(); stopwatch.Restart();
#endif #endif
int counter = 0; int counter = 0;
foreach(DbFile file in files) foreach(DbFile file in files)
{ {
UpdateProgress2?.Invoke($"Scanning file {counter} of {files.Count}", null, counter, files.Count); UpdateProgress2?.Invoke($"Scanning file {counter} of {files.Count}", null, counter, files.Count);
@@ -285,6 +312,7 @@ namespace apprepodbmgr.Core
} }
#if DEBUG #if DEBUG
stopwatch.Stop(); stopwatch.Stop();
Console.WriteLine("Core.ClamScanAllFiles(): Took {0} seconds scan all pending files", Console.WriteLine("Core.ClamScanAllFiles(): Took {0} seconds scan all pending files",
stopwatch.Elapsed.TotalSeconds); stopwatch.Elapsed.TotalSeconds);
#endif #endif

View File

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

View File

@@ -46,6 +46,7 @@ namespace apprepodbmgr.Core
dbCore.DbOps.GetAllApps(out List<DbEntry> apps); dbCore.DbOps.GetAllApps(out List<DbEntry> apps);
#if DEBUG #if DEBUG
stopwatch.Stop(); stopwatch.Stop();
Console.WriteLine("Core.GetAllApps(): Took {0} seconds to get apps from database", Console.WriteLine("Core.GetAllApps(): Took {0} seconds to get apps from database",
stopwatch.Elapsed.TotalSeconds); stopwatch.Elapsed.TotalSeconds);
#endif #endif
@@ -56,17 +57,20 @@ namespace apprepodbmgr.Core
stopwatch.Restart(); stopwatch.Restart();
#endif #endif
int counter = 0; int counter = 0;
// TODO: Check file name and existence // TODO: Check file name and existence
foreach(DbEntry app in apps) foreach(DbEntry app in apps)
{ {
UpdateProgress?.Invoke("Populating apps table", $"{app.Developer} {app.Product}", counter, UpdateProgress?.Invoke("Populating apps table", $"{app.Developer} {app.Product}", counter,
apps.Count); apps.Count);
AddApp?.Invoke(app); AddApp?.Invoke(app);
counter++; counter++;
} }
#if DEBUG #if DEBUG
stopwatch.Stop(); stopwatch.Stop();
Console.WriteLine("Core.GetAllApps(): Took {0} seconds to add apps to the GUI", Console.WriteLine("Core.GetAllApps(): Took {0} seconds to add apps to the GUI",
stopwatch.Elapsed.TotalSeconds); stopwatch.Elapsed.TotalSeconds);
#endif #endif
@@ -74,10 +78,11 @@ namespace apprepodbmgr.Core
Finished?.Invoke(); Finished?.Invoke();
} }
catch(ThreadAbortException) { } catch(ThreadAbortException) {}
catch(Exception ex) catch(Exception ex)
{ {
if(Debugger.IsAttached) throw; if(Debugger.IsAttached)
throw;
Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}");
#if DEBUG #if DEBUG
@@ -105,6 +110,7 @@ namespace apprepodbmgr.Core
{ {
AddFileForApp(kvp.Key, kvp.Value.Sha256, true, kvp.Value.Crack); AddFileForApp(kvp.Key, kvp.Value.Sha256, true, kvp.Value.Crack);
counter++; counter++;
continue; continue;
} }
@@ -118,17 +124,21 @@ namespace apprepodbmgr.Core
counter++; counter++;
knownFiles.Add(kvp.Key, kvp.Value); knownFiles.Add(kvp.Key, kvp.Value);
} }
else unknownFile = true; else
unknownFile = true;
} }
#if DEBUG #if DEBUG
stopwatch.Stop(); stopwatch.Stop();
Console.WriteLine("Core.CheckDbForFiles(): Took {0} seconds to checks for file knowledge in the DB", Console.WriteLine("Core.CheckDbForFiles(): Took {0} seconds to checks for file knowledge in the DB",
stopwatch.Elapsed.TotalSeconds); stopwatch.Elapsed.TotalSeconds);
stopwatch.Restart(); stopwatch.Restart();
#endif #endif
if(knownFiles.Count == 0 || unknownFile) if(knownFiles.Count == 0 || unknownFile)
{ {
Finished?.Invoke(); Finished?.Invoke();
return; return;
} }
@@ -136,11 +146,13 @@ namespace apprepodbmgr.Core
dbCore.DbOps.GetAllApps(out List<DbEntry> apps); dbCore.DbOps.GetAllApps(out List<DbEntry> apps);
#if DEBUG #if DEBUG
stopwatch.Stop(); stopwatch.Stop();
Console.WriteLine("Core.CheckDbForFiles(): Took {0} seconds get all apps from DB", Console.WriteLine("Core.CheckDbForFiles(): Took {0} seconds get all apps from DB",
stopwatch.Elapsed.TotalSeconds); stopwatch.Elapsed.TotalSeconds);
#endif #endif
if(apps != null && apps.Count > 0) if(apps != null &&
apps.Count > 0)
{ {
DbEntry[] appsArray = new DbEntry[apps.Count]; DbEntry[] appsArray = new DbEntry[apps.Count];
apps.CopyTo(appsArray); apps.CopyTo(appsArray);
@@ -155,6 +167,7 @@ namespace apprepodbmgr.Core
UpdateProgress?.Invoke(null, $"Check application id {app.Id}", appCounter, appsArray.Length); UpdateProgress?.Invoke(null, $"Check application id {app.Id}", appCounter, appsArray.Length);
counter = 0; counter = 0;
foreach(KeyValuePair<string, DbAppFile> kvp in knownFiles) foreach(KeyValuePair<string, DbAppFile> kvp in knownFiles)
{ {
UpdateProgress2?.Invoke(null, $"Checking for file {kvp.Value.Path}", counter, 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(!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 // If one file is missing, the rest don't matter
break; break;
@@ -171,10 +185,12 @@ namespace apprepodbmgr.Core
counter++; counter++;
} }
if(apps.Count == 0) break; // No apps left if(apps.Count == 0)
break; // No apps left
} }
#if DEBUG #if DEBUG
stopwatch.Stop(); stopwatch.Stop();
Console.WriteLine("Core.CheckDbForFiles(): Took {0} seconds correlate all files with all known applications", Console.WriteLine("Core.CheckDbForFiles(): Took {0} seconds correlate all files with all known applications",
stopwatch.Elapsed.TotalSeconds); stopwatch.Elapsed.TotalSeconds);
#endif #endif
@@ -186,10 +202,11 @@ namespace apprepodbmgr.Core
Finished?.Invoke(); Finished?.Invoke();
} }
catch(ThreadAbortException) { } catch(ThreadAbortException) {}
catch(Exception ex) catch(Exception ex)
{ {
if(Debugger.IsAttached) throw; if(Debugger.IsAttached)
throw;
Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}");
#if DEBUG #if DEBUG
@@ -212,7 +229,7 @@ namespace apprepodbmgr.Core
if(!dbCore.DbOps.ExistsFile(kvp.Value.Sha256)) if(!dbCore.DbOps.ExistsFile(kvp.Value.Sha256))
{ {
DbFile file = new DbFile var file = new DbFile
{ {
Sha256 = kvp.Value.Sha256, Sha256 = kvp.Value.Sha256,
ClamTime = null, ClamTime = null,
@@ -222,6 +239,7 @@ namespace apprepodbmgr.Core
HasVirus = null, HasVirus = null,
VirusTotalTime = null VirusTotalTime = null
}; };
dbCore.DbOps.AddFile(file); dbCore.DbOps.AddFile(file);
AddFile?.Invoke(file); AddFile?.Invoke(file);
@@ -231,6 +249,7 @@ namespace apprepodbmgr.Core
} }
#if DEBUG #if DEBUG
stopwatch.Stop(); stopwatch.Stop();
Console.WriteLine("Core.AddFilesToDb(): Took {0} seconds to add all files to the database", Console.WriteLine("Core.AddFilesToDb(): Took {0} seconds to add all files to the database",
stopwatch.Elapsed.TotalSeconds); stopwatch.Elapsed.TotalSeconds);
#endif #endif
@@ -244,6 +263,7 @@ namespace apprepodbmgr.Core
stopwatch.Restart(); stopwatch.Restart();
#endif #endif
counter = 0; counter = 0;
foreach(KeyValuePair<string, DbAppFile> kvp in Context.Hashes) foreach(KeyValuePair<string, DbAppFile> kvp in Context.Hashes)
{ {
UpdateProgress?.Invoke(null, "Adding files to application in database", counter, UpdateProgress?.Invoke(null, "Adding files to application in database", counter,
@@ -255,11 +275,14 @@ namespace apprepodbmgr.Core
} }
#if DEBUG #if DEBUG
stopwatch.Stop(); stopwatch.Stop();
Console.WriteLine("Core.AddFilesToDb(): Took {0} seconds to add all files to the application in the database", Console.WriteLine("Core.AddFilesToDb(): Took {0} seconds to add all files to the application in the database",
stopwatch.Elapsed.TotalSeconds); stopwatch.Elapsed.TotalSeconds);
stopwatch.Restart(); stopwatch.Restart();
#endif #endif
counter = 0; counter = 0;
foreach(KeyValuePair<string, DbFolder> kvp in Context.FoldersDict) foreach(KeyValuePair<string, DbFolder> kvp in Context.FoldersDict)
{ {
UpdateProgress?.Invoke(null, "Adding folders to application in database", counter, UpdateProgress?.Invoke(null, "Adding folders to application in database", counter,
@@ -271,12 +294,16 @@ namespace apprepodbmgr.Core
} }
#if DEBUG #if DEBUG
stopwatch.Stop(); stopwatch.Stop();
Console.WriteLine("Core.AddFilesToDb(): Took {0} seconds to add all folders to the database", Console.WriteLine("Core.AddFilesToDb(): Took {0} seconds to add all folders to the database",
stopwatch.Elapsed.TotalSeconds); stopwatch.Elapsed.TotalSeconds);
stopwatch.Restart(); stopwatch.Restart();
#endif #endif
counter = 0; 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) foreach(KeyValuePair<string, string> kvp in Context.SymlinksDict)
{ {
@@ -289,16 +316,18 @@ namespace apprepodbmgr.Core
} }
#if DEBUG #if DEBUG
stopwatch.Stop(); stopwatch.Stop();
Console.WriteLine("Core.AddFilesToDb(): Took {0} seconds to add all symbolic links to the database", Console.WriteLine("Core.AddFilesToDb(): Took {0} seconds to add all symbolic links to the database",
stopwatch.Elapsed.TotalSeconds); stopwatch.Elapsed.TotalSeconds);
#endif #endif
Finished?.Invoke(); Finished?.Invoke();
} }
catch(ThreadAbortException) { } catch(ThreadAbortException) {}
catch(Exception ex) catch(Exception ex)
{ {
if(Debugger.IsAttached) throw; if(Debugger.IsAttached)
throw;
Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}");
#if DEBUG #if DEBUG
@@ -317,16 +346,19 @@ namespace apprepodbmgr.Core
if(string.IsNullOrEmpty(Settings.Current.DatabasePath)) if(string.IsNullOrEmpty(Settings.Current.DatabasePath))
{ {
Failed?.Invoke("No database file specified"); Failed?.Invoke("No database file specified");
return; return;
} }
dbCore = new SQLite(); dbCore = new SQLite();
if(File.Exists(Settings.Current.DatabasePath)) if(File.Exists(Settings.Current.DatabasePath))
{ {
if(!dbCore.OpenDb(Settings.Current.DatabasePath, null, null, null)) if(!dbCore.OpenDb(Settings.Current.DatabasePath, null, null, null))
{ {
Failed?.Invoke("Could not open database, correct file selected?"); Failed?.Invoke("Could not open database, correct file selected?");
dbCore = null; dbCore = null;
return; return;
} }
} }
@@ -336,6 +368,7 @@ namespace apprepodbmgr.Core
{ {
Failed?.Invoke("Could not create database, correct file selected?"); Failed?.Invoke("Could not create database, correct file selected?");
dbCore = null; dbCore = null;
return; return;
} }
@@ -343,16 +376,18 @@ namespace apprepodbmgr.Core
{ {
Failed?.Invoke("Could not open database, correct file selected?"); Failed?.Invoke("Could not open database, correct file selected?");
dbCore = null; dbCore = null;
return; return;
} }
} }
Finished?.Invoke(); Finished?.Invoke();
} }
catch(ThreadAbortException) { } catch(ThreadAbortException) {}
catch(Exception ex) catch(Exception ex)
{ {
if(Debugger.IsAttached) throw; if(Debugger.IsAttached)
throw;
Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}");
#if DEBUG #if DEBUG
@@ -361,14 +396,13 @@ namespace apprepodbmgr.Core
} }
} }
public static void CloseDB() public static void CloseDB() => dbCore?.CloseDb();
{
dbCore?.CloseDb();
}
public static void RemoveApp(long id, string mdid) 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); dbCore.DbOps.RemoveApp(id);
} }
@@ -386,7 +420,8 @@ namespace apprepodbmgr.Core
#endif #endif
while(dbCore.DbOps.GetFiles(out List<DbFile> files, offset, PAGE)) 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); UpdateProgress?.Invoke(null, $"Loaded file {offset} of {count}", (long)offset, (long)count);
@@ -396,16 +431,18 @@ namespace apprepodbmgr.Core
} }
#if DEBUG #if DEBUG
stopwatch.Stop(); stopwatch.Stop();
Console.WriteLine("Core.GetFilesFromDb(): Took {0} seconds to get all files from the database", Console.WriteLine("Core.GetFilesFromDb(): Took {0} seconds to get all files from the database",
stopwatch.Elapsed.TotalSeconds); stopwatch.Elapsed.TotalSeconds);
#endif #endif
Finished?.Invoke(); Finished?.Invoke();
} }
catch(ThreadAbortException) { } catch(ThreadAbortException) {}
catch(Exception ex) catch(Exception ex)
{ {
if(Debugger.IsAttached) throw; if(Debugger.IsAttached)
throw;
Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}");
#if DEBUG #if DEBUG
@@ -422,10 +459,11 @@ namespace apprepodbmgr.Core
Finished?.Invoke(); Finished?.Invoke();
} }
catch(ThreadAbortException) { } catch(ThreadAbortException) {}
catch(Exception ex) catch(Exception ex)
{ {
if(Debugger.IsAttached) throw; if(Debugger.IsAttached)
throw;
Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}");
#if DEBUG #if DEBUG
@@ -434,9 +472,6 @@ namespace apprepodbmgr.Core
} }
} }
public static DbFile GetDBFile(string hash) public static DbFile GetDBFile(string hash) => dbCore.DbOps.GetFile(hash);
{
return 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

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

View File

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

View File

@@ -40,9 +40,12 @@ namespace apprepodbmgr.Eto.Desktop
{ {
Settings.LoadSettings(); Settings.LoadSettings();
Context.CheckUnar(); Context.CheckUnar();
if(Settings.Current.UseAntivirus) if(Settings.Current.UseAntivirus)
{ {
if(Settings.Current.UseClamd) Workers.InitClamd(); if(Settings.Current.UseClamd)
Workers.InitClamd();
if(Settings.Current.UseVirusTotal) if(Settings.Current.UseVirusTotal)
Context.VirusTotalEnabled = Workers.InitVirusTotal(Settings.Current.VirusTotalKey); Context.VirusTotalEnabled = Workers.InitVirusTotal(Settings.Current.VirusTotalKey);
} }

View File

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

View File

@@ -47,9 +47,9 @@ namespace apprepodbmgr.Eto
{ {
public delegate void OnAddedAppDelegate(DbEntry app); public delegate void OnAddedAppDelegate(DbEntry app);
ObservableCollection<DBEntryForEto> appView; readonly ObservableCollection<DBEntryForEto> appView;
ObservableCollection<FileEntry> fileView; readonly ObservableCollection<FileEntry> fileView;
int knownFiles; int knownFiles;
bool stopped; bool stopped;
Thread thdAddFiles; Thread thdAddFiles;
@@ -74,22 +74,37 @@ namespace apprepodbmgr.Eto
treeFiles.Columns.Add(new GridColumn treeFiles.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell {Binding = Binding.Property<FileEntry, string>(r => r.Path)}, DataCell = new TextBoxCell
{
Binding = Binding.Property<FileEntry, string>(r => r.Path)
},
HeaderText = "Path" HeaderText = "Path"
}); });
treeFiles.Columns.Add(new GridColumn treeFiles.Columns.Add(new GridColumn
{ {
DataCell = new CheckBoxCell {Binding = Binding.Property<FileEntry, bool?>(r => r.IsCrack)}, DataCell = new CheckBoxCell
{
Binding = Binding.Property<FileEntry, bool?>(r => r.IsCrack)
},
HeaderText = "Crack?" HeaderText = "Crack?"
}); });
treeFiles.Columns.Add(new GridColumn treeFiles.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell {Binding = Binding.Property<FileEntry, string>(r => r.Hash)}, DataCell = new TextBoxCell
{
Binding = Binding.Property<FileEntry, string>(r => r.Hash)
},
HeaderText = "SHA256" HeaderText = "SHA256"
}); });
treeFiles.Columns.Add(new GridColumn treeFiles.Columns.Add(new GridColumn
{ {
DataCell = new CheckBoxCell {Binding = Binding.Property<FileEntry, bool?>(r => r.Known)}, DataCell = new CheckBoxCell
{
Binding = Binding.Property<FileEntry, bool?>(r => r.Known)
},
HeaderText = "Known?" HeaderText = "Known?"
}); });
@@ -106,72 +121,127 @@ namespace apprepodbmgr.Eto
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell {Binding = Binding.Property<DBEntryForEto, string>(r => r.developer)}, DataCell = new TextBoxCell
{
Binding = Binding.Property<DBEntryForEto, string>(r => r.developer)
},
HeaderText = "Developer" HeaderText = "Developer"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell {Binding = Binding.Property<DBEntryForEto, string>(r => r.product)}, DataCell = new TextBoxCell
{
Binding = Binding.Property<DBEntryForEto, string>(r => r.product)
},
HeaderText = "Product" HeaderText = "Product"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell {Binding = Binding.Property<DBEntryForEto, string>(r => r.version)}, DataCell = new TextBoxCell
{
Binding = Binding.Property<DBEntryForEto, string>(r => r.version)
},
HeaderText = "Version" HeaderText = "Version"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell {Binding = Binding.Property<DBEntryForEto, string>(r => r.languages)}, DataCell = new TextBoxCell
{
Binding = Binding.Property<DBEntryForEto, string>(r => r.languages)
},
HeaderText = "Languages" HeaderText = "Languages"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell {Binding = Binding.Property<DBEntryForEto, string>(r => r.architecture)}, DataCell = new TextBoxCell
{
Binding = Binding.Property<DBEntryForEto, string>(r => r.architecture)
},
HeaderText = "Architecture" HeaderText = "Architecture"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell {Binding = Binding.Property<DBEntryForEto, string>(r => r.targetos)}, DataCell = new TextBoxCell
{
Binding = Binding.Property<DBEntryForEto, string>(r => r.targetos)
},
HeaderText = "Target OS" HeaderText = "Target OS"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell {Binding = Binding.Property<DBEntryForEto, string>(r => r.format)}, DataCell = new TextBoxCell
{
Binding = Binding.Property<DBEntryForEto, string>(r => r.format)
},
HeaderText = "Format" HeaderText = "Format"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell {Binding = Binding.Property<DBEntryForEto, string>(r => r.description)}, DataCell = new TextBoxCell
{
Binding = Binding.Property<DBEntryForEto, string>(r => r.description)
},
HeaderText = "Description" HeaderText = "Description"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new CheckBoxCell {Binding = Binding.Property<DBEntryForEto, bool?>(r => r.oem)}, DataCell = new CheckBoxCell
{
Binding = Binding.Property<DBEntryForEto, bool?>(r => r.oem)
},
HeaderText = "OEM?" HeaderText = "OEM?"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new CheckBoxCell {Binding = Binding.Property<DBEntryForEto, bool?>(r => r.upgrade)}, DataCell = new CheckBoxCell
{
Binding = Binding.Property<DBEntryForEto, bool?>(r => r.upgrade)
},
HeaderText = "Upgrade?" HeaderText = "Upgrade?"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new CheckBoxCell {Binding = Binding.Property<DBEntryForEto, bool?>(r => r.update)}, DataCell = new CheckBoxCell
{
Binding = Binding.Property<DBEntryForEto, bool?>(r => r.update)
},
HeaderText = "Update?" HeaderText = "Update?"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new CheckBoxCell {Binding = Binding.Property<DBEntryForEto, bool?>(r => r.source)}, DataCell = new CheckBoxCell
{
Binding = Binding.Property<DBEntryForEto, bool?>(r => r.source)
},
HeaderText = "Source?" HeaderText = "Source?"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new CheckBoxCell {Binding = Binding.Property<DBEntryForEto, bool?>(r => r.files)}, DataCell = new CheckBoxCell
{
Binding = Binding.Property<DBEntryForEto, bool?>(r => r.files)
},
HeaderText = "Files?" HeaderText = "Files?"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new CheckBoxCell {Binding = Binding.Property<DBEntryForEto, bool?>(r => r.Installer)}, DataCell = new CheckBoxCell
{
Binding = Binding.Property<DBEntryForEto, bool?>(r => r.Installer)
},
HeaderText = "Installer?" HeaderText = "Installer?"
}); });
@@ -179,29 +249,43 @@ namespace apprepodbmgr.Eto
txtArchitecture.ToolTip = txtArchitecture.ToolTip =
"This field contains a comma separated list of architectures the application can run on. To edit its contents use the metadata editor."; "This field contains a comma separated list of architectures the application can run on. To edit its contents use the metadata editor.";
txtDescription.ToolTip = "This field contains a free-form text description of this application."; txtDescription.ToolTip = "This field contains a free-form text description of this application.";
txtDeveloper.ToolTip = txtDeveloper.ToolTip =
"This field contains the developer of the application. To edit its contents use the metadata editor."; "This field contains the developer of the application. To edit its contents use the metadata editor.";
txtFormat.ToolTip = txtFormat.ToolTip =
"This field is contains the name of the format of the disk images, when it is not a byte-by-byte format like .iso or .img."; "This field is contains the name of the format of the disk images, when it is not a byte-by-byte format like .iso or .img.";
txtLanguages.ToolTip = txtLanguages.ToolTip =
"This field contains a comma separated list of languages the application includes. To edit its contents use the metadata editor."; "This field contains a comma separated list of languages the application includes. To edit its contents use the metadata editor.";
txtProduct.ToolTip = txtProduct.ToolTip =
"This field contains the application name. To edit its contents use the metadata editor."; "This field contains the application name. To edit its contents use the metadata editor.";
txtTargetOs.ToolTip = txtTargetOs.ToolTip =
"This field contains a comma separated list of operating systems this application can run on. To edit its contents use the metadata editor."; "This field contains a comma separated list of operating systems this application can run on. To edit its contents use the metadata editor.";
txtVersion.ToolTip = txtVersion.ToolTip =
"This field contains the application version. To edit its contents use the metadata editor."; "This field contains the application version. To edit its contents use the metadata editor.";
chkFiles.ToolTip = "If this field is checked it indicates the application is already installed."; chkFiles.ToolTip = "If this field is checked it indicates the application is already installed.";
chkInstaller.ToolTip = chkInstaller.ToolTip =
"If this field is checked it indicates the application comes as an installer (one or several files), but it's not installed neither disk images."; "If this field is checked it indicates the application comes as an installer (one or several files), but it's not installed neither disk images.";
chkOem.ToolTip = chkOem.ToolTip =
"If this field is checked it indicates the application came bundled with hardware (aka OEM distributed)."; "If this field is checked it indicates the application came bundled with hardware (aka OEM distributed).";
chkSource.ToolTip = "If this field is checked it indicates this is the source code for the application."; chkSource.ToolTip = "If this field is checked it indicates this is the source code for the application.";
chkUpdate.ToolTip = chkUpdate.ToolTip =
"If this field is checked it indicates this version is a minor version update that requires a previous version of the application already installed."; "If this field is checked it indicates this version is a minor version update that requires a previous version of the application already installed.";
chkUpgrade.ToolTip = chkUpgrade.ToolTip =
"If this field is checked it indicates this version is a major version upgrade that requires a previous version of the application already installed."; "If this field is checked it indicates this version is a major version upgrade that requires a previous version of the application already installed.";
txtArchitecture.ReadOnly = true; txtArchitecture.ReadOnly = true;
txtDeveloper.ReadOnly = true; txtDeveloper.ReadOnly = true;
txtLanguages.ReadOnly = true; txtLanguages.ReadOnly = true;
@@ -212,22 +296,29 @@ namespace apprepodbmgr.Eto
public event OnAddedAppDelegate OnAddedApp; public event OnAddedAppDelegate OnAddedApp;
void UnarChangeStatus() void UnarChangeStatus() => Application.Instance.Invoke(delegate
{ {
Application.Instance.Invoke(delegate { btnArchive.Enabled = Context.UnarUsable; }); btnArchive.Enabled = Context.UnarUsable;
} });
protected void OnDeleteEvent(object sender, CancelEventArgs e) protected void OnDeleteEvent(object sender, CancelEventArgs e)
{ {
if(btnStop.Visible) btnStop.PerformClick(); if(btnStop.Visible)
if(btnClose.Enabled) btnClose.PerformClick(); btnStop.PerformClick();
if(btnClose.Enabled)
btnClose.PerformClick();
} }
protected void OnBtnFolderClicked(object sender, EventArgs e) protected void OnBtnFolderClicked(object sender, EventArgs e)
{ {
SelectFolderDialog dlgFolder = new SelectFolderDialog {Title = "Open folder"}; var dlgFolder = new SelectFolderDialog
{
Title = "Open folder"
};
if(dlgFolder.ShowDialog(this) != DialogResult.Ok) return; if(dlgFolder.ShowDialog(this) != DialogResult.Ok)
return;
knownFiles = 0; knownFiles = 0;
stopped = false; stopped = false;
@@ -245,11 +336,11 @@ namespace apprepodbmgr.Eto
thdFindFiles.Start(); thdFindFiles.Start();
} }
void FindFilesFailed(string text) void FindFilesFailed(string text) => Application.Instance.Invoke(delegate
{ {
Application.Instance.Invoke(delegate if(!stopped)
{ MessageBox.Show(text, MessageBoxType.Error);
if(!stopped) MessageBox.Show(text, MessageBoxType.Error);
lblProgress.Visible = false; lblProgress.Visible = false;
prgProgress.Visible = false; prgProgress.Visible = false;
btnExit.Enabled = true; btnExit.Enabled = true;
@@ -260,11 +351,8 @@ namespace apprepodbmgr.Eto
Workers.Finished -= FindFilesFinished; Workers.Finished -= FindFilesFinished;
thdFindFiles = null; thdFindFiles = null;
}); });
}
void FindFilesFinished() void FindFilesFinished() => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
Workers.Failed -= FindFilesFailed; Workers.Failed -= FindFilesFailed;
Workers.Finished -= FindFilesFinished; Workers.Finished -= FindFilesFinished;
@@ -282,13 +370,12 @@ namespace apprepodbmgr.Eto
Workers.UpdateProgress2 += UpdateProgress2; Workers.UpdateProgress2 += UpdateProgress2;
thdHashFiles.Start(); thdHashFiles.Start();
}); });
}
void HashFilesFailed(string text) void HashFilesFailed(string text) => Application.Instance.Invoke(delegate
{ {
Application.Instance.Invoke(delegate if(!stopped)
{ MessageBox.Show(text, MessageBoxType.Error);
if(!stopped) MessageBox.Show(text, MessageBoxType.Error);
lblProgress.Visible = false; lblProgress.Visible = false;
prgProgress.Visible = false; prgProgress.Visible = false;
lblProgress2.Visible = false; lblProgress2.Visible = false;
@@ -303,11 +390,8 @@ namespace apprepodbmgr.Eto
btnStop.Visible = false; btnStop.Visible = false;
thdHashFiles = null; thdHashFiles = null;
}); });
}
void HashFilesFinished() void HashFilesFinished() => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
lblProgress.Visible = false; lblProgress.Visible = false;
prgProgress.Visible = false; prgProgress.Visible = false;
@@ -331,13 +415,12 @@ namespace apprepodbmgr.Eto
Workers.AddApp += AddApp; Workers.AddApp += AddApp;
thdCheckFiles.Start(); thdCheckFiles.Start();
}); });
}
void ChkFilesFailed(string text) void ChkFilesFailed(string text) => Application.Instance.Invoke(delegate
{ {
Application.Instance.Invoke(delegate if(!stopped)
{ MessageBox.Show(text, MessageBoxType.Error);
if(!stopped) MessageBox.Show(text, MessageBoxType.Error);
prgProgress.Visible = false; prgProgress.Visible = false;
btnStop.Visible = false; btnStop.Visible = false;
btnClose.Visible = false; btnClose.Visible = false;
@@ -351,16 +434,15 @@ namespace apprepodbmgr.Eto
thdCheckFiles?.Abort(); thdCheckFiles?.Abort();
thdHashFiles = null; thdHashFiles = null;
fileView?.Clear(); fileView?.Clear();
if(appView == null) return;
if(appView == null)
return;
tabApps.Visible = false; tabApps.Visible = false;
appView.Clear(); appView.Clear();
}); });
}
void ChkFilesFinished() void ChkFilesFinished() => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
Workers.Failed -= ChkFilesFailed; Workers.Failed -= ChkFilesFailed;
Workers.Finished -= ChkFilesFinished; Workers.Finished -= ChkFilesFinished;
@@ -376,21 +458,22 @@ namespace apprepodbmgr.Eto
prgProgress.Visible = false; prgProgress.Visible = false;
btnStop.Visible = false; btnStop.Visible = false;
if(Context.Executables?.Count > 0 || Context.Readmes?.Count > 0) if(Context.Executables?.Count > 0 ||
Context.Readmes?.Count > 0)
{ {
dlgImportMetadata importMetadataDlg = new dlgImportMetadata(); var importMetadataDlg = new dlgImportMetadata();
importMetadataDlg.ShowModal(this); importMetadataDlg.ShowModal(this);
if(!importMetadataDlg.canceled && (importMetadataDlg.chosenArchitectures.Count > 0 || if(!importMetadataDlg.canceled &&
importMetadataDlg.chosenOses.Count > 0 || (importMetadataDlg.chosenArchitectures.Count > 0 || importMetadataDlg.chosenOses.Count > 0 ||
!string.IsNullOrWhiteSpace(importMetadataDlg.description) || !string.IsNullOrWhiteSpace(importMetadataDlg.description) ||
!string.IsNullOrWhiteSpace(importMetadataDlg.developer) || !string.IsNullOrWhiteSpace(importMetadataDlg.developer) ||
!string.IsNullOrWhiteSpace(importMetadataDlg.product) || !string.IsNullOrWhiteSpace(importMetadataDlg.product) ||
!string.IsNullOrWhiteSpace(importMetadataDlg.publisher) || !string.IsNullOrWhiteSpace(importMetadataDlg.publisher) ||
!string.IsNullOrWhiteSpace(importMetadataDlg.version))) !string.IsNullOrWhiteSpace(importMetadataDlg.version)))
{ {
if(Context.Metadata == null && (importMetadataDlg.chosenArchitectures.Count > 0 || if(Context.Metadata == null &&
importMetadataDlg.chosenOses.Count > 0 || (importMetadataDlg.chosenArchitectures.Count > 0 || importMetadataDlg.chosenOses.Count > 0 ||
!string.IsNullOrWhiteSpace(importMetadataDlg.developer) || !string.IsNullOrWhiteSpace(importMetadataDlg.developer) ||
!string.IsNullOrWhiteSpace(importMetadataDlg.product) || !string.IsNullOrWhiteSpace(importMetadataDlg.product) ||
!string.IsNullOrWhiteSpace(importMetadataDlg.publisher) || !string.IsNullOrWhiteSpace(importMetadataDlg.publisher) ||
@@ -399,12 +482,21 @@ namespace apprepodbmgr.Eto
if(!string.IsNullOrWhiteSpace(importMetadataDlg.description)) if(!string.IsNullOrWhiteSpace(importMetadataDlg.description))
txtDescription.Text = importMetadataDlg.description; txtDescription.Text = importMetadataDlg.description;
if(!string.IsNullOrWhiteSpace(importMetadataDlg.product)) if(!string.IsNullOrWhiteSpace(importMetadataDlg.product))
Context.Metadata.Name = importMetadataDlg.product; Context.Metadata.Name = importMetadataDlg.product;
if(!string.IsNullOrWhiteSpace(importMetadataDlg.publisher)) if(!string.IsNullOrWhiteSpace(importMetadataDlg.publisher))
Context.Metadata.Publisher = new[] {importMetadataDlg.publisher}; Context.Metadata.Publisher = new[]
{
importMetadataDlg.publisher
};
if(!string.IsNullOrWhiteSpace(importMetadataDlg.developer)) if(!string.IsNullOrWhiteSpace(importMetadataDlg.developer))
Context.Metadata.Developer = new[] {importMetadataDlg.developer}; Context.Metadata.Developer = new[]
{
importMetadataDlg.developer
};
if(importMetadataDlg.chosenArchitectures.Count > 0) if(importMetadataDlg.chosenArchitectures.Count > 0)
Context.Metadata.Architectures = importMetadataDlg.chosenArchitectures.ToArray(); Context.Metadata.Architectures = importMetadataDlg.chosenArchitectures.ToArray();
@@ -412,11 +504,15 @@ namespace apprepodbmgr.Eto
if(importMetadataDlg.chosenOses.Count > 0) if(importMetadataDlg.chosenOses.Count > 0)
{ {
List<RequiredOperatingSystemType> reqOs = new List<RequiredOperatingSystemType>(); List<RequiredOperatingSystemType> reqOs = new List<RequiredOperatingSystemType>();
foreach(TargetOsEntry osEntry in importMetadataDlg.chosenOses) foreach(TargetOsEntry osEntry in importMetadataDlg.chosenOses)
reqOs.Add(new RequiredOperatingSystemType reqOs.Add(new RequiredOperatingSystemType
{ {
Name = osEntry.name, Name = osEntry.name,
Version = new[] {osEntry.version} Version = new[]
{
osEntry.version
}
}); });
Context.Metadata.RequiredOperatingSystems = reqOs.ToArray(); Context.Metadata.RequiredOperatingSystems = reqOs.ToArray();
@@ -443,71 +539,87 @@ namespace apprepodbmgr.Eto
chkSource.Enabled = true; chkSource.Enabled = true;
btnMetadata.Visible = true; btnMetadata.Visible = true;
if(Context.Metadata != null) if(Context.Metadata != null)
{ {
if(Context.Metadata.Developer != null) if(Context.Metadata.Developer != null)
foreach(string developer in Context.Metadata.Developer) foreach(string developer in Context.Metadata.Developer)
{ {
if(!string.IsNullOrWhiteSpace(txtDeveloper.Text)) txtDeveloper.Text += ","; if(!string.IsNullOrWhiteSpace(txtDeveloper.Text))
txtDeveloper.Text += ",";
txtDeveloper.Text += developer; txtDeveloper.Text += developer;
} }
if(!string.IsNullOrWhiteSpace(Context.Metadata.Name)) txtProduct.Text = Context.Metadata.Name; if(!string.IsNullOrWhiteSpace(Context.Metadata.Name))
if(!string.IsNullOrWhiteSpace(Context.Metadata.Version)) txtVersion.Text = Context.Metadata.Version; txtProduct.Text = Context.Metadata.Name;
if(!string.IsNullOrWhiteSpace(Context.Metadata.Version))
txtVersion.Text = Context.Metadata.Version;
if(Context.Metadata.Languages != null) if(Context.Metadata.Languages != null)
foreach(LanguagesTypeLanguage language in Context.Metadata.Languages) foreach(LanguagesTypeLanguage language in Context.Metadata.Languages)
{ {
if(!string.IsNullOrWhiteSpace(txtLanguages.Text)) txtLanguages.Text += ","; if(!string.IsNullOrWhiteSpace(txtLanguages.Text))
txtLanguages.Text += ",";
txtLanguages.Text += language; txtLanguages.Text += language;
} }
if(Context.Metadata.Architectures != null) if(Context.Metadata.Architectures != null)
foreach(ArchitecturesTypeArchitecture architecture in Context.Metadata.Architectures) foreach(ArchitecturesTypeArchitecture architecture in Context.Metadata.Architectures)
{ {
if(!string.IsNullOrWhiteSpace(txtArchitecture.Text)) txtArchitecture.Text += ","; if(!string.IsNullOrWhiteSpace(txtArchitecture.Text))
txtArchitecture.Text += ",";
txtArchitecture.Text += architecture; txtArchitecture.Text += architecture;
} }
if(Context.Metadata.RequiredOperatingSystems != null) if(Context.Metadata.RequiredOperatingSystems != null)
foreach(string targetos in Context foreach(string targetos in Context.Metadata.RequiredOperatingSystems.Select(os => os.Name).
.Metadata.RequiredOperatingSystems.Select(os => os.Name).Distinct()) Distinct())
{ {
if(!string.IsNullOrWhiteSpace(txtTargetOs.Text)) txtTargetOs.Text += ","; if(!string.IsNullOrWhiteSpace(txtTargetOs.Text))
txtTargetOs.Text += ",";
txtTargetOs.Text += targetos; txtTargetOs.Text += targetos;
} }
btnMetadata.BackgroundColor = Colors.Green; btnMetadata.BackgroundColor = Colors.Green;
} }
else btnMetadata.BackgroundColor = Colors.Red; else
btnMetadata.BackgroundColor = Colors.Red;
lblStatus.Visible = true; lblStatus.Visible = true;
lblStatus.Text = $"{fileView.Count} files ({knownFiles} already known)"; lblStatus.Text = $"{fileView.Count} files ({knownFiles} already known)";
}); });
}
void AddFile(string filename, string hash, bool known, bool isCrack) void AddFile(string filename, string hash, bool known, bool isCrack) => Application.Instance.Invoke(delegate
{ {
Application.Instance.Invoke(delegate fileView.Add(new FileEntry
{ {
fileView.Add(new FileEntry {Path = filename, Hash = hash, Known = known, IsCrack = isCrack}); Path = filename,
btnPack.Enabled |= !known; Hash = hash,
if(known) knownFiles++; Known = known,
IsCrack = isCrack
}); });
}
void AddApp(DbEntry app) btnPack.Enabled |= !known;
{
Application.Instance.Invoke(delegate if(known)
knownFiles++;
});
void AddApp(DbEntry app) => Application.Instance.Invoke(delegate
{ {
tabApps.Visible = true; tabApps.Visible = true;
appView.Add(new DBEntryForEto(app)); appView.Add(new DBEntryForEto(app));
}); });
}
protected void OnBtnExitClicked(object sender, EventArgs e) protected void OnBtnExitClicked(object sender, EventArgs e)
{ {
if(btnClose.Enabled) OnBtnCloseClicked(sender, e); if(btnClose.Enabled)
OnBtnCloseClicked(sender, e);
Close(); Close();
} }
@@ -527,6 +639,7 @@ namespace apprepodbmgr.Eto
btnRemoveFile.Visible = false; btnRemoveFile.Visible = false;
btnToggleCrack.Visible = false; btnToggleCrack.Visible = false;
fileView?.Clear(); fileView?.Clear();
if(appView != null) if(appView != null)
{ {
tabApps.Visible = false; tabApps.Visible = false;
@@ -574,17 +687,22 @@ namespace apprepodbmgr.Eto
lblStatus.Visible = false; lblStatus.Visible = false;
} }
void UpdateProgress(string text, string inner, long current, long maximum) void UpdateProgress(string text, string inner, long current, long maximum) =>
{
Application.Instance.Invoke(delegate Application.Instance.Invoke(delegate
{ {
if(!string.IsNullOrWhiteSpace(text) && !string.IsNullOrWhiteSpace(inner)) if(!string.IsNullOrWhiteSpace(text) &&
!string.IsNullOrWhiteSpace(inner))
lblProgress.Text = $"{text}: {inner}"; lblProgress.Text = $"{text}: {inner}";
else if(!string.IsNullOrWhiteSpace(inner)) lblProgress.Text = inner; else if(!string.IsNullOrWhiteSpace(inner))
else lblProgress.Text = text; lblProgress.Text = inner;
else
lblProgress.Text = text;
if(maximum > 0) if(maximum > 0)
{ {
if(current < int.MinValue || current > int.MaxValue || maximum < int.MinValue || if(current < int.MinValue ||
current > int.MaxValue ||
maximum < int.MinValue ||
maximum > int.MaxValue) maximum > int.MaxValue)
{ {
current /= 100; current /= 100;
@@ -596,21 +714,26 @@ namespace apprepodbmgr.Eto
prgProgress.MaxValue = (int)maximum; prgProgress.MaxValue = (int)maximum;
prgProgress.Value = (int)current; prgProgress.Value = (int)current;
} }
else prgProgress.Indeterminate = true; else
prgProgress.Indeterminate = true;
}); });
}
void UpdateProgress2(string text, string inner, long current, long maximum) void UpdateProgress2(string text, string inner, long current, long maximum) =>
{
Application.Instance.Invoke(delegate Application.Instance.Invoke(delegate
{ {
if(!string.IsNullOrWhiteSpace(text) && !string.IsNullOrWhiteSpace(inner)) if(!string.IsNullOrWhiteSpace(text) &&
!string.IsNullOrWhiteSpace(inner))
lblProgress2.Text = $"{text}: {inner}"; lblProgress2.Text = $"{text}: {inner}";
else if(!string.IsNullOrWhiteSpace(inner)) lblProgress2.Text = inner; else if(!string.IsNullOrWhiteSpace(inner))
else lblProgress2.Text = text; lblProgress2.Text = inner;
else
lblProgress2.Text = text;
if(maximum > 0) if(maximum > 0)
{ {
if(current < int.MinValue || current > int.MaxValue || maximum < int.MinValue || if(current < int.MinValue ||
current > int.MaxValue ||
maximum < int.MinValue ||
maximum > int.MaxValue) maximum > int.MaxValue)
{ {
current /= 100; current /= 100;
@@ -622,9 +745,9 @@ namespace apprepodbmgr.Eto
prgProgress2.MaxValue = (int)maximum; prgProgress2.MaxValue = (int)maximum;
prgProgress2.Value = (int)current; prgProgress2.Value = (int)current;
} }
else prgProgress2.Indeterminate = true; else
prgProgress2.Indeterminate = true;
}); });
}
protected void OnBtnStopClicked(object sender, EventArgs e) protected void OnBtnStopClicked(object sender, EventArgs e)
{ {
@@ -703,7 +826,8 @@ namespace apprepodbmgr.Eto
thdRemoveTemp = new Thread(Workers.RemoveTempFolder); thdRemoveTemp = new Thread(Workers.RemoveTempFolder);
thdRemoveTemp.Start(); thdRemoveTemp.Start();
} }
else RestoreUi(); else
RestoreUi();
} }
void RestoreUi() void RestoreUi()
@@ -740,15 +864,15 @@ namespace apprepodbmgr.Eto
Workers.UpdateProgress2 -= UpdateProgress2; Workers.UpdateProgress2 -= UpdateProgress2;
btnStop.Visible = false; btnStop.Visible = false;
fileView?.Clear(); fileView?.Clear();
if(appView == null) return;
if(appView == null)
return;
tabApps.Visible = false; tabApps.Visible = false;
appView.Clear(); appView.Clear();
} }
void RemoveTempFilesFailed(string text) void RemoveTempFilesFailed(string text) => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
MessageBox.Show(text, MessageBoxType.Error); MessageBox.Show(text, MessageBoxType.Error);
Workers.Failed -= RemoveTempFilesFailed; Workers.Failed -= RemoveTempFilesFailed;
@@ -757,11 +881,8 @@ namespace apprepodbmgr.Eto
Context.TmpFolder = null; Context.TmpFolder = null;
RestoreUi(); RestoreUi();
}); });
}
void RemoveTempFilesFinished() void RemoveTempFilesFinished() => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
Workers.Failed -= RemoveTempFilesFailed; Workers.Failed -= RemoveTempFilesFailed;
Workers.Finished -= RemoveTempFilesFinished; Workers.Finished -= RemoveTempFilesFinished;
@@ -769,7 +890,6 @@ namespace apprepodbmgr.Eto
Context.TmpFolder = null; Context.TmpFolder = null;
RestoreUi(); RestoreUi();
}); });
}
void AddToDatabase() void AddToDatabase()
{ {
@@ -808,13 +928,13 @@ namespace apprepodbmgr.Eto
if(Context.Metadata != null) if(Context.Metadata != null)
{ {
MemoryStream ms = new MemoryStream(); var ms = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(CICMMetadataType)); var xs = new XmlSerializer(typeof(CICMMetadataType));
xs.Serialize(ms, Context.Metadata); xs.Serialize(ms, Context.Metadata);
Context.DbInfo.Xml = ms.ToArray(); Context.DbInfo.Xml = ms.ToArray();
JsonSerializer js = new JsonSerializer(); var js = new JsonSerializer();
ms = new MemoryStream(); ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms); var sw = new StreamWriter(ms);
js.Serialize(sw, Context.Metadata, typeof(CICMMetadataType)); js.Serialize(sw, Context.Metadata, typeof(CICMMetadataType));
Context.DbInfo.Json = ms.ToArray(); Context.DbInfo.Json = ms.ToArray();
} }
@@ -828,9 +948,7 @@ namespace apprepodbmgr.Eto
thdAddFiles.Start(); thdAddFiles.Start();
} }
void AddFilesToDbFinished() void AddFilesToDbFinished() => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
Workers.UpdateProgress -= UpdateProgress; Workers.UpdateProgress -= UpdateProgress;
Workers.Finished -= AddFilesToDbFinished; Workers.Finished -= AddFilesToDbFinished;
@@ -840,10 +958,18 @@ namespace apprepodbmgr.Eto
long counter = 0; long counter = 0;
fileView.Clear(); fileView.Clear();
foreach(KeyValuePair<string, DbAppFile> kvp in Context.Hashes) foreach(KeyValuePair<string, DbAppFile> kvp in Context.Hashes)
{ {
UpdateProgress(null, "Updating table", counter, Context.Hashes.Count); UpdateProgress(null, "Updating table", counter, Context.Hashes.Count);
fileView.Add(new FileEntry {Path = kvp.Key, Hash = kvp.Value.Sha256, Known = true});
fileView.Add(new FileEntry
{
Path = kvp.Key,
Hash = kvp.Value.Sha256,
Known = true
});
counter++; counter++;
} }
@@ -855,13 +981,11 @@ namespace apprepodbmgr.Eto
prgProgress.Visible = false; prgProgress.Visible = false;
btnClose.Enabled = true; btnClose.Enabled = true;
}); });
}
void AddFilesToDbFailed(string text) void AddFilesToDbFailed(string text) => Application.Instance.Invoke(delegate
{ {
Application.Instance.Invoke(delegate if(!stopped)
{ MessageBox.Show(text, MessageBoxType.Error);
if(!stopped) MessageBox.Show(text, MessageBoxType.Error);
Workers.UpdateProgress -= UpdateProgress; Workers.UpdateProgress -= UpdateProgress;
Workers.Finished -= AddFilesToDbFinished; Workers.Finished -= AddFilesToDbFinished;
@@ -871,7 +995,6 @@ namespace apprepodbmgr.Eto
ChkFilesFinished(); ChkFilesFinished();
}); });
}
protected void OnBtnPackClicked(object sender, EventArgs e) protected void OnBtnPackClicked(object sender, EventArgs e)
{ {
@@ -916,9 +1039,7 @@ namespace apprepodbmgr.Eto
thdPackFiles.Start(); thdPackFiles.Start();
} }
void PackFilesFinished(string text) void PackFilesFinished(string text) => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
Workers.UpdateProgress -= UpdateProgress; Workers.UpdateProgress -= UpdateProgress;
Workers.UpdateProgress2 -= UpdateProgress2; Workers.UpdateProgress2 -= UpdateProgress2;
@@ -933,13 +1054,11 @@ namespace apprepodbmgr.Eto
MessageBox.Show(text); MessageBox.Show(text);
}); });
}
void PackFilesFailed(string text) void PackFilesFailed(string text) => Application.Instance.Invoke(delegate
{ {
Application.Instance.Invoke(delegate if(!stopped)
{ MessageBox.Show(text, MessageBoxType.Error);
if(!stopped) MessageBox.Show(text, MessageBoxType.Error);
Workers.UpdateProgress -= UpdateProgress; Workers.UpdateProgress -= UpdateProgress;
Workers.UpdateProgress2 -= UpdateProgress2; Workers.UpdateProgress2 -= UpdateProgress2;
@@ -965,19 +1084,24 @@ namespace apprepodbmgr.Eto
chkInstaller.Enabled = true; chkInstaller.Enabled = true;
chkSource.Enabled = true; chkSource.Enabled = true;
}); });
}
protected void OnBtnArchiveClicked(object sender, EventArgs e) protected void OnBtnArchiveClicked(object sender, EventArgs e)
{ {
if(!Context.UnarUsable) if(!Context.UnarUsable)
{ {
MessageBox.Show("Cannot open archives without a working unar installation.", MessageBoxType.Error); MessageBox.Show("Cannot open archives without a working unar installation.", MessageBoxType.Error);
return; return;
} }
OpenFileDialog dlgFile = new OpenFileDialog {Title = "Open archive", MultiSelect = false}; var dlgFile = new OpenFileDialog
{
Title = "Open archive",
MultiSelect = false
};
if(dlgFile.ShowDialog(this) != DialogResult.Ok) return; if(dlgFile.ShowDialog(this) != DialogResult.Ok)
return;
knownFiles = 0; knownFiles = 0;
stopped = false; stopped = false;
@@ -997,11 +1121,11 @@ namespace apprepodbmgr.Eto
thdOpenArchive.Start(); thdOpenArchive.Start();
} }
void OpenArchiveFailed(string text) void OpenArchiveFailed(string text) => Application.Instance.Invoke(delegate
{ {
Application.Instance.Invoke(delegate if(!stopped)
{ MessageBox.Show(text, MessageBoxType.Error);
if(!stopped) MessageBox.Show(text, MessageBoxType.Error);
lblProgress.Visible = false; lblProgress.Visible = false;
prgProgress.Visible = false; prgProgress.Visible = false;
btnExit.Enabled = true; btnExit.Enabled = true;
@@ -1012,11 +1136,8 @@ namespace apprepodbmgr.Eto
Workers.Finished -= OpenArchiveFinished; Workers.Finished -= OpenArchiveFinished;
thdOpenArchive = null; thdOpenArchive = null;
}); });
}
void OpenArchiveFinished() void OpenArchiveFinished() => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
stopped = false; stopped = false;
lblProgress.Text = "Extracting archive"; lblProgress.Text = "Extracting archive";
@@ -1037,13 +1158,12 @@ namespace apprepodbmgr.Eto
thdExtractArchive = new Thread(Workers.ExtractArchive); thdExtractArchive = new Thread(Workers.ExtractArchive);
thdExtractArchive.Start(); thdExtractArchive.Start();
}); });
}
void ExtractArchiveFailed(string text) void ExtractArchiveFailed(string text) => Application.Instance.Invoke(delegate
{ {
Application.Instance.Invoke(delegate if(!stopped)
{ MessageBox.Show(text, MessageBoxType.Error);
if(!stopped) MessageBox.Show(text, MessageBoxType.Error);
lblProgress2.Visible = false; lblProgress2.Visible = false;
prgProgress2.Visible = false; prgProgress2.Visible = false;
btnExit.Enabled = true; btnExit.Enabled = true;
@@ -1054,7 +1174,9 @@ namespace apprepodbmgr.Eto
Workers.UpdateProgress -= UpdateProgress; Workers.UpdateProgress -= UpdateProgress;
Workers.UpdateProgress2 -= UpdateProgress2; Workers.UpdateProgress2 -= UpdateProgress2;
thdExtractArchive = null; thdExtractArchive = null;
if(Context.TmpFolder == null) return;
if(Context.TmpFolder == null)
return;
btnStop.Visible = false; btnStop.Visible = false;
lblProgress.Text = "Removing temporary files"; lblProgress.Text = "Removing temporary files";
@@ -1064,11 +1186,8 @@ namespace apprepodbmgr.Eto
thdRemoveTemp = new Thread(Workers.RemoveTempFolder); thdRemoveTemp = new Thread(Workers.RemoveTempFolder);
thdRemoveTemp.Start(); thdRemoveTemp.Start();
}); });
}
void ExtractArchiveFinished() void ExtractArchiveFinished() => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
stopped = false; stopped = false;
lblProgress.Text = "Finding files"; lblProgress.Text = "Finding files";
@@ -1091,16 +1210,20 @@ namespace apprepodbmgr.Eto
btnStop.Visible = true; btnStop.Visible = true;
thdFindFiles.Start(); thdFindFiles.Start();
}); });
}
protected void OnBtnMetadataClicked(object sender, EventArgs e) protected void OnBtnMetadataClicked(object sender, EventArgs e)
{ {
dlgMetadata _dlgMetadata = new dlgMetadata {Metadata = Context.Metadata}; var _dlgMetadata = new dlgMetadata
{
Metadata = Context.Metadata
};
_dlgMetadata.FillFields(); _dlgMetadata.FillFields();
_dlgMetadata.ShowModal(this); _dlgMetadata.ShowModal(this);
if(!_dlgMetadata.Modified) return; if(!_dlgMetadata.Modified)
return;
Context.Metadata = _dlgMetadata.Metadata; Context.Metadata = _dlgMetadata.Metadata;
@@ -1108,7 +1231,9 @@ namespace apprepodbmgr.Eto
if(Context.Metadata.Developer != null) if(Context.Metadata.Developer != null)
foreach(string developer in Context.Metadata.Developer) foreach(string developer in Context.Metadata.Developer)
{ {
if(!string.IsNullOrWhiteSpace(txtDeveloper.Text)) txtDeveloper.Text += ","; if(!string.IsNullOrWhiteSpace(txtDeveloper.Text))
txtDeveloper.Text += ",";
txtDeveloper.Text += developer; txtDeveloper.Text += developer;
} }
@@ -1124,7 +1249,9 @@ namespace apprepodbmgr.Eto
if(Context.Metadata.Languages != null) if(Context.Metadata.Languages != null)
foreach(LanguagesTypeLanguage language in Context.Metadata.Languages) foreach(LanguagesTypeLanguage language in Context.Metadata.Languages)
{ {
if(!string.IsNullOrWhiteSpace(txtLanguages.Text)) txtLanguages.Text += ","; if(!string.IsNullOrWhiteSpace(txtLanguages.Text))
txtLanguages.Text += ",";
txtLanguages.Text += language; txtLanguages.Text += language;
} }
@@ -1132,16 +1259,20 @@ namespace apprepodbmgr.Eto
if(Context.Metadata.Architectures != null) if(Context.Metadata.Architectures != null)
foreach(ArchitecturesTypeArchitecture architecture in Context.Metadata.Architectures) foreach(ArchitecturesTypeArchitecture architecture in Context.Metadata.Architectures)
{ {
if(!string.IsNullOrWhiteSpace(txtArchitecture.Text)) txtArchitecture.Text += ","; if(!string.IsNullOrWhiteSpace(txtArchitecture.Text))
txtArchitecture.Text += ",";
txtArchitecture.Text += architecture; txtArchitecture.Text += architecture;
} }
if(string.IsNullOrWhiteSpace(txtTargetOs.Text)) if(string.IsNullOrWhiteSpace(txtTargetOs.Text))
if(Context.Metadata.RequiredOperatingSystems != null) if(Context.Metadata.RequiredOperatingSystems != null)
foreach(string targetos in Context.Metadata.RequiredOperatingSystems.Select(os => os.Name) foreach(string targetos in Context.Metadata.RequiredOperatingSystems.Select(os => os.Name).
.Distinct()) Distinct())
{ {
if(!string.IsNullOrWhiteSpace(txtTargetOs.Text)) txtTargetOs.Text += ","; if(!string.IsNullOrWhiteSpace(txtTargetOs.Text))
txtTargetOs.Text += ",";
txtTargetOs.Text += targetos; txtTargetOs.Text += targetos;
} }
@@ -1150,14 +1281,17 @@ namespace apprepodbmgr.Eto
protected void OnBtnRemoveFileClicked(object sender, EventArgs e) protected void OnBtnRemoveFileClicked(object sender, EventArgs e)
{ {
if(treeFiles.SelectedItem == null) return; if(treeFiles.SelectedItem == null)
return;
string name = ((FileEntry)treeFiles.SelectedItem).Path; string name = ((FileEntry)treeFiles.SelectedItem).Path;
string filesPath; string filesPath;
if(!string.IsNullOrEmpty(Context.TmpFolder) && Directory.Exists(Context.TmpFolder)) if(!string.IsNullOrEmpty(Context.TmpFolder) &&
Directory.Exists(Context.TmpFolder))
filesPath = Context.TmpFolder; filesPath = Context.TmpFolder;
else filesPath = Context.Path; else
filesPath = Context.Path;
Context.Hashes.Remove(name); Context.Hashes.Remove(name);
Context.Files.Remove(Path.Combine(filesPath, name)); Context.Files.Remove(Path.Combine(filesPath, name));
@@ -1166,24 +1300,34 @@ namespace apprepodbmgr.Eto
protected void OnBtnToggleCrackClicked(object sender, EventArgs e) protected void OnBtnToggleCrackClicked(object sender, EventArgs e)
{ {
if(treeFiles.SelectedItem == null) return; if(treeFiles.SelectedItem == null)
return;
string name = ((FileEntry)treeFiles.SelectedItem).Path; string name = ((FileEntry)treeFiles.SelectedItem).Path;
bool known = ((FileEntry)treeFiles.SelectedItem).Known; bool known = ((FileEntry)treeFiles.SelectedItem).Known;
if(!Context.Hashes.TryGetValue(name, out DbAppFile appFile)) return; if(!Context.Hashes.TryGetValue(name, out DbAppFile appFile))
return;
appFile.Crack = !appFile.Crack; appFile.Crack = !appFile.Crack;
Context.Hashes.Remove(name); Context.Hashes.Remove(name);
Context.Hashes.Add(name, appFile); Context.Hashes.Add(name, appFile);
((FileEntry)treeFiles.SelectedItem).IsCrack = appFile.Crack; ((FileEntry)treeFiles.SelectedItem).IsCrack = appFile.Crack;
fileView.Remove((FileEntry)treeFiles.SelectedItem); fileView.Remove((FileEntry)treeFiles.SelectedItem);
fileView.Add(new FileEntry {Path = name, Hash = appFile.Sha256, Known = known, IsCrack = appFile.Crack});
fileView.Add(new FileEntry
{
Path = name,
Hash = appFile.Sha256,
Known = known,
IsCrack = appFile.Crack
});
} }
void treeFilesSelectionChanged(object sender, EventArgs e) void treeFilesSelectionChanged(object sender, EventArgs e)
{ {
if(treeFiles.SelectedItem == null) return; if(treeFiles.SelectedItem == null)
return;
btnToggleCrack.Text = ((FileEntry)treeFiles.SelectedItem).IsCrack ? "Mark as not crack" : "Mark as crack"; btnToggleCrack.Text = ((FileEntry)treeFiles.SelectedItem).IsCrack ? "Mark as not crack" : "Mark as crack";
} }

File diff suppressed because it is too large Load Diff

View File

@@ -46,9 +46,12 @@ namespace apprepodbmgr.Eto
public void FillFields() 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) if(Metadata.CreationDateSpecified)
{ {
chkCreationDate.Checked = true; chkCreationDate.Checked = true;
@@ -72,12 +75,23 @@ namespace apprepodbmgr.Eto
spClusterSize.Value = Metadata.ClusterSize; spClusterSize.Value = Metadata.ClusterSize;
txtClusters.Text = Metadata.Clusters.ToString(); txtClusters.Text = Metadata.Clusters.ToString();
if(Metadata.FilesSpecified) txtFiles.Text = Metadata.Files.ToString();
if(Metadata.FilesSpecified)
txtFiles.Text = Metadata.Files.ToString();
chkBootable.Checked = Metadata.Bootable; chkBootable.Checked = Metadata.Bootable;
if(Metadata.VolumeSerial != null) txtSerial.Text = Metadata.VolumeSerial;
if(Metadata.VolumeName != null) txtLabel.Text = Metadata.VolumeName; if(Metadata.VolumeSerial != null)
if(Metadata.FreeClustersSpecified) txtFreeClusters.Text = Metadata.FreeClusters.ToString(); txtSerial.Text = Metadata.VolumeSerial;
if(Metadata.VolumeName != null)
txtLabel.Text = Metadata.VolumeName;
if(Metadata.FreeClustersSpecified)
txtFreeClusters.Text = Metadata.FreeClusters.ToString();
chkDirty.Checked = Metadata.Dirty; chkDirty.Checked = Metadata.Dirty;
if(Metadata.ExpirationDateSpecified) if(Metadata.ExpirationDateSpecified)
{ {
chkExpirationDate.Checked = true; chkExpirationDate.Checked = true;
@@ -92,37 +106,36 @@ namespace apprepodbmgr.Eto
cldEffectiveDate.Value = Metadata.EffectiveDate; cldEffectiveDate.Value = Metadata.EffectiveDate;
} }
if(Metadata.SystemIdentifier != null) txtSysId.Text = Metadata.SystemIdentifier; if(Metadata.SystemIdentifier != null)
if(Metadata.VolumeSetIdentifier != null) txtVolId.Text = Metadata.VolumeSetIdentifier; txtSysId.Text = Metadata.SystemIdentifier;
if(Metadata.PublisherIdentifier != null) txtPubId.Text = Metadata.PublisherIdentifier;
if(Metadata.DataPreparerIdentifier != null) txtDataId.Text = Metadata.DataPreparerIdentifier; if(Metadata.VolumeSetIdentifier != null)
if(Metadata.ApplicationIdentifier != null) txtAppId.Text = Metadata.ApplicationIdentifier; 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; cldCreationDate.Enabled = chkCreationDate.Checked.Value;
}
protected void OnChkModificationDateToggled(object sender, EventArgs e) protected void OnChkModificationDateToggled(object sender, EventArgs e) =>
{
cldModificationDate.Enabled = chkModificationDate.Checked.Value; cldModificationDate.Enabled = chkModificationDate.Checked.Value;
}
protected void OnChkEffectiveDateToggled(object sender, EventArgs e) protected void OnChkEffectiveDateToggled(object sender, EventArgs e) =>
{
cldEffectiveDate.Enabled = chkEffectiveDate.Checked.Value; cldEffectiveDate.Enabled = chkEffectiveDate.Checked.Value;
}
protected void OnChkExpirationDateToggled(object sender, EventArgs e) protected void OnChkExpirationDateToggled(object sender, EventArgs e) =>
{
cldExpirationDate.Enabled = chkExpirationDate.Checked.Value; cldExpirationDate.Enabled = chkExpirationDate.Checked.Value;
}
protected void OnChkBackupDateToggled(object sender, EventArgs e) protected void OnChkBackupDateToggled(object sender, EventArgs e) =>
{
cldBackupDate.Enabled = chkBackupDate.Checked.Value; cldBackupDate.Enabled = chkBackupDate.Checked.Value;
}
protected void OnBtnCancelClicked(object sender, EventArgs e) protected void OnBtnCancelClicked(object sender, EventArgs e)
{ {
@@ -135,26 +148,36 @@ namespace apprepodbmgr.Eto
if(string.IsNullOrWhiteSpace(txtType.Text)) if(string.IsNullOrWhiteSpace(txtType.Text))
MessageBox.Show("Filesystem type cannot be empty", MessageBoxType.Error); 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)) if(!long.TryParse(txtClusters.Text, out long temp))
MessageBox.Show("Clusters must be a number", MessageBoxType.Error); 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); 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); 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); 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); 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) if(chkCreationDate.Checked.Value)
{ {
Metadata.CreationDateSpecified = true; Metadata.CreationDateSpecified = true;
@@ -175,6 +198,7 @@ namespace apprepodbmgr.Eto
Metadata.ClusterSize = (int)spClusterSize.Value; Metadata.ClusterSize = (int)spClusterSize.Value;
Metadata.Clusters = long.Parse(txtClusters.Text); Metadata.Clusters = long.Parse(txtClusters.Text);
if(!string.IsNullOrWhiteSpace(txtFiles.Text)) if(!string.IsNullOrWhiteSpace(txtFiles.Text))
{ {
Metadata.FilesSpecified = true; Metadata.FilesSpecified = true;
@@ -182,8 +206,13 @@ namespace apprepodbmgr.Eto
} }
Metadata.Bootable = chkBootable.Checked.Value; 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(txtSerial.Text))
Metadata.VolumeSerial = txtSerial.Text;
if(!string.IsNullOrWhiteSpace(txtLabel.Text))
Metadata.VolumeName = txtLabel.Text;
if(!string.IsNullOrWhiteSpace(txtFreeClusters.Text)) if(!string.IsNullOrWhiteSpace(txtFreeClusters.Text))
{ {
Metadata.FreeClustersSpecified = true; Metadata.FreeClustersSpecified = true;
@@ -191,6 +220,7 @@ namespace apprepodbmgr.Eto
} }
Metadata.Dirty = chkDirty.Checked.Value; Metadata.Dirty = chkDirty.Checked.Value;
if(chkExpirationDate.Checked.Value) if(chkExpirationDate.Checked.Value)
{ {
Metadata.ExpirationDateSpecified = true; Metadata.ExpirationDateSpecified = true;
@@ -203,11 +233,20 @@ namespace apprepodbmgr.Eto
Metadata.EffectiveDate = cldEffectiveDate.Value.Value; Metadata.EffectiveDate = cldEffectiveDate.Value.Value;
} }
if(!string.IsNullOrWhiteSpace(txtSysId.Text)) Metadata.SystemIdentifier = txtSysId.Text; if(!string.IsNullOrWhiteSpace(txtSysId.Text))
if(!string.IsNullOrWhiteSpace(txtVolId.Text)) Metadata.VolumeSetIdentifier = txtVolId.Text; Metadata.SystemIdentifier = txtSysId.Text;
if(!string.IsNullOrWhiteSpace(txtPubId.Text)) Metadata.PublisherIdentifier = txtPubId.Text;
if(!string.IsNullOrWhiteSpace(txtDataId.Text)) Metadata.DataPreparerIdentifier = txtDataId.Text; if(!string.IsNullOrWhiteSpace(txtVolId.Text))
if(!string.IsNullOrWhiteSpace(txtAppId.Text)) Metadata.ApplicationIdentifier = txtAppId.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; Modified = true;
Close(); Close();

View File

@@ -22,9 +22,9 @@ namespace apprepodbmgr.Eto
Panels maximumPanel; Panels maximumPanel;
Panels minimumPanel; Panels minimumPanel;
List<TargetOsEntry> operatingSystems; List<TargetOsEntry> operatingSystems;
pnlDescription panelDescription; readonly pnlDescription panelDescription;
pnlStrings panelStrings; readonly pnlStrings panelStrings;
pnlVersions panelVersions; readonly pnlVersions panelVersions;
internal string product; internal string product;
internal string publisher; internal string publisher;
List<string> strings; List<string> strings;
@@ -75,37 +75,49 @@ namespace apprepodbmgr.Eto
foreach(string file in Context.Executables) foreach(string file in Context.Executables)
{ {
FileStream exeStream = new FileStream(file, FileMode.Open, FileAccess.Read); var exeStream = new FileStream(file, FileMode.Open, FileAccess.Read);
MZ mzExe = new MZ(exeStream); var mzExe = new MZ(exeStream);
NE neExe = new NE(exeStream); var neExe = new NE(exeStream);
AtariST stExe = new AtariST(exeStream); var stExe = new AtariST(exeStream);
LX lxExe = new LX(exeStream); var lxExe = new LX(exeStream);
COFF coffExe = new COFF(exeStream); var coffExe = new COFF(exeStream);
PE peExe = new PE(exeStream); var peExe = new PE(exeStream);
Geos geosExe = new Geos(exeStream); var geosExe = new Geos(exeStream);
ELF elfExe = new ELF(exeStream); var elfExe = new ELF(exeStream);
IExecutable recognizedExe; IExecutable recognizedExe;
if(neExe.Recognized) recognizedExe = neExe; if(neExe.Recognized)
else if(lxExe.Recognized) recognizedExe = lxExe; recognizedExe = neExe;
else if(peExe.Recognized) recognizedExe = peExe; else if(lxExe.Recognized)
else if(mzExe.Recognized) recognizedExe = mzExe; recognizedExe = lxExe;
else if(coffExe.Recognized) recognizedExe = coffExe; else if(peExe.Recognized)
else if(stExe.Recognized) recognizedExe = stExe; recognizedExe = peExe;
else if(elfExe.Recognized) recognizedExe = elfExe; else if(mzExe.Recognized)
else if(geosExe.Recognized) recognizedExe = geosExe; 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 else
{ {
exeStream.Close(); exeStream.Close();
continue; continue;
} }
if(recognizedExe.Strings != null) strings.AddRange(recognizedExe.Strings); if(recognizedExe.Strings != null)
strings.AddRange(recognizedExe.Strings);
foreach(Architecture exeArch in recognizedExe.Architectures) foreach(Architecture exeArch in recognizedExe.Architectures)
{ {
ArchitecturesTypeArchitecture? arch = ExeArchToSchemaArch(exeArch); ArchitecturesTypeArchitecture? arch = ExeArchToSchemaArch(exeArch);
if(arch.HasValue && !architectures.Contains($"{arch.Value}"))
if(arch.HasValue &&
!architectures.Contains($"{arch.Value}"))
architectures.Add($"{arch.Value}"); architectures.Add($"{arch.Value}");
} }
@@ -125,11 +137,13 @@ namespace apprepodbmgr.Eto
versions.Add(exeVersion.FileVersion); versions.Add(exeVersion.FileVersion);
versions.Add(exeVersion.ProductVersion); versions.Add(exeVersion.ProductVersion);
version = 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)) if(kvp.Value.TryGetValue("CompanyName", out string tmpValue))
developer = tmpValue; developer = tmpValue;
if(kvp.Value.TryGetValue("ProductName", out string tmpValue2)) if(kvp.Value.TryGetValue("ProductName", out string tmpValue2))
product = tmpValue2; product = tmpValue2;
} }
@@ -143,11 +157,13 @@ namespace apprepodbmgr.Eto
versions.Add(exeVersion.FileVersion); versions.Add(exeVersion.FileVersion);
versions.Add(exeVersion.ProductVersion); versions.Add(exeVersion.ProductVersion);
version = 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)) if(kvp.Value.TryGetValue("CompanyName", out string tmpValue))
developer = tmpValue; developer = tmpValue;
if(kvp.Value.TryGetValue("ProductName", out string tmpValue2)) if(kvp.Value.TryGetValue("ProductName", out string tmpValue2))
product = tmpValue2; product = tmpValue2;
} }
@@ -160,12 +176,15 @@ namespace apprepodbmgr.Eto
versions.Add(lxExe.WinVersion.FileVersion); versions.Add(lxExe.WinVersion.FileVersion);
versions.Add(lxExe.WinVersion.ProductVersion); versions.Add(lxExe.WinVersion.ProductVersion);
version = lxExe.WinVersion.ProductVersion; version = lxExe.WinVersion.ProductVersion;
foreach(KeyValuePair<string, Dictionary<string, string>> kvp in lxExe
.WinVersion foreach(KeyValuePair<string, Dictionary<string, string>> kvp in lxExe.WinVersion.
.StringsByLanguage) StringsByLanguage)
{ {
if(kvp.Value.TryGetValue("CompanyName", out string tmpValue)) developer = tmpValue; if(kvp.Value.TryGetValue("CompanyName", out string tmpValue))
if(kvp.Value.TryGetValue("ProductName", out string tmpValue2)) product = tmpValue2; developer = tmpValue;
if(kvp.Value.TryGetValue("ProductName", out string tmpValue2))
product = tmpValue2;
} }
} }
@@ -179,8 +198,11 @@ namespace apprepodbmgr.Eto
strings = strings.Distinct().ToList(); strings = strings.Distinct().ToList();
strings.Sort(); strings.Sort();
if(strings.Count == 0 && minimumPanel == Panels.Strings) minimumPanel = Panels.Versions; if(strings.Count == 0 &&
else maximumPanel = Panels.Strings; minimumPanel == Panels.Strings)
minimumPanel = Panels.Versions;
else
maximumPanel = Panels.Strings;
panelStrings.treeStrings.DataStore = strings; panelStrings.treeStrings.DataStore = strings;
versions = versions.Distinct().ToList(); versions = versions.Distinct().ToList();
@@ -194,11 +216,13 @@ namespace apprepodbmgr.Eto
foreach(TargetOsEntry osEntry in operatingSystems) 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); 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); osvers.Add(osEntry.version);
osEntriesDictionary.Remove(osEntry.name); osEntriesDictionary.Remove(osEntry.name);
@@ -206,38 +230,52 @@ namespace apprepodbmgr.Eto
} }
operatingSystems = new List<TargetOsEntry>(); operatingSystems = new List<TargetOsEntry>();
foreach(KeyValuePair<string, List<string>> kvp in osEntriesDictionary.OrderBy(t => t.Key)) foreach(KeyValuePair<string, List<string>> kvp in osEntriesDictionary.OrderBy(t => t.Key))
{ {
kvp.Value.Sort(); kvp.Value.Sort();
foreach(string s in kvp.Value.Distinct()) 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; 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; maximumPanel = Panels.Versions;
} }
prgProgress.Visible = false; prgProgress.Visible = false;
btnPrevious.Enabled = false; btnPrevious.Enabled = false;
switch(minimumPanel) switch(minimumPanel)
{ {
case Panels.Description: case Panels.Description:
pnlPanel.Content = panelDescription; pnlPanel.Content = panelDescription;
currentPanel = Panels.Description; currentPanel = Panels.Description;
break; break;
case Panels.Strings: case Panels.Strings:
pnlPanel.Content = panelStrings; pnlPanel.Content = panelStrings;
currentPanel = Panels.Strings; currentPanel = Panels.Strings;
break; break;
case Panels.Versions: case Panels.Versions:
pnlPanel.Content = panelVersions; pnlPanel.Content = panelVersions;
currentPanel = Panels.Versions; currentPanel = Panels.Versions;
break; break;
} }
if(currentPanel == maximumPanel) btnNext.Text = "Finish"; if(currentPanel == maximumPanel)
btnNext.Text = "Finish";
lblPanelName.Visible = false; lblPanelName.Visible = false;
} }
@@ -297,6 +335,7 @@ namespace apprepodbmgr.Eto
{ {
canceled = true; canceled = true;
Close(); Close();
// throw new NotImplementedException(); // throw new NotImplementedException();
} }
@@ -308,7 +347,8 @@ namespace apprepodbmgr.Eto
// Ok... // Ok...
break; break;
case Panels.Strings: case Panels.Strings:
if(minimumPanel == Panels.Strings) return; if(minimumPanel == Panels.Strings)
return;
pnlPanel.Content = panelDescription; pnlPanel.Content = panelDescription;
currentPanel = Panels.Description; currentPanel = Panels.Description;
@@ -317,7 +357,8 @@ namespace apprepodbmgr.Eto
break; break;
case Panels.Versions: case Panels.Versions:
if(minimumPanel == Panels.Versions) return; if(minimumPanel == Panels.Versions)
return;
pnlPanel.Content = panelStrings; pnlPanel.Content = panelStrings;
currentPanel = Panels.Strings; currentPanel = Panels.Strings;
@@ -327,7 +368,8 @@ namespace apprepodbmgr.Eto
break; break;
} }
if(currentPanel != maximumPanel) btnNext.Text = "Next"; if(currentPanel != maximumPanel)
btnNext.Text = "Next";
} }
void OnBtnNextClick(object sender, EventArgs eventArgs) void OnBtnNextClick(object sender, EventArgs eventArgs)
@@ -337,7 +379,8 @@ namespace apprepodbmgr.Eto
switch(currentPanel) switch(currentPanel)
{ {
case Panels.Description: case Panels.Description:
if(maximumPanel == Panels.Description) return; if(maximumPanel == Panels.Description)
return;
pnlPanel.Content = panelStrings; pnlPanel.Content = panelStrings;
currentPanel = Panels.Strings; currentPanel = Panels.Strings;
@@ -346,7 +389,8 @@ namespace apprepodbmgr.Eto
break; break;
case Panels.Strings: case Panels.Strings:
if(maximumPanel == Panels.Strings) return; if(maximumPanel == Panels.Strings)
return;
pnlPanel.Content = panelVersions; pnlPanel.Content = panelVersions;
currentPanel = Panels.Versions; currentPanel = Panels.Versions;
@@ -355,7 +399,8 @@ namespace apprepodbmgr.Eto
break; break;
case Panels.Versions: case Panels.Versions:
if(minimumPanel == Panels.Versions) return; if(minimumPanel == Panels.Versions)
return;
pnlPanel.Content = panelStrings; pnlPanel.Content = panelStrings;
currentPanel = Panels.Strings; currentPanel = Panels.Strings;
@@ -365,23 +410,35 @@ namespace apprepodbmgr.Eto
break; break;
} }
if(currentPanel == maximumPanel) btnNext.Text = "Finish"; if(currentPanel == maximumPanel)
btnNext.Text = "Finish";
return; return;
} }
if(Context.Readmes?.Count > 0 && !string.IsNullOrWhiteSpace(panelDescription.description)) if(Context.Readmes?.Count > 0 &&
!string.IsNullOrWhiteSpace(panelDescription.description))
description = 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.txtDeveloper.Text))
if(!string.IsNullOrWhiteSpace(panelStrings.txtPublisher.Text)) publisher = panelStrings.txtPublisher.Text; developer = panelStrings.txtDeveloper.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.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) 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)) if(Enum.TryParse(arch, true, out ArchitecturesTypeArchitecture realArch))
chosenArchitectures.Add(realArch); chosenArchitectures.Add(realArch);
@@ -389,12 +446,14 @@ namespace apprepodbmgr.Eto
foreach(object osesSelectedItem in panelVersions.treeOs.SelectedItems) foreach(object osesSelectedItem in panelVersions.treeOs.SelectedItems)
{ {
if(!(osesSelectedItem is TargetOsEntry os)) continue; if(!(osesSelectedItem is TargetOsEntry os))
continue;
chosenOses.Add(os); chosenOses.Add(os);
} }
if(panelVersions.treeVersions.SelectedItem is string chosenVersion) version = chosenVersion; if(panelVersions.treeVersions.SelectedItem is string chosenVersion)
version = chosenVersion;
canceled = false; canceled = false;
Close(); Close();
@@ -402,9 +461,7 @@ namespace apprepodbmgr.Eto
enum Panels enum Panels
{ {
Description, Description, Strings, Versions
Strings,
Versions
} }
#region XAML UI elements #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; txtDatabase.Text = Settings.Current.DatabasePath;
txtRepository.Text = Settings.Current.RepositoryPath; txtRepository.Text = Settings.Current.RepositoryPath;
if(!string.IsNullOrWhiteSpace(txtUnar.Text)) CheckUnar(); if(!string.IsNullOrWhiteSpace(txtUnar.Text))
CheckUnar();
cmbCompAlg = new EnumDropDown<AlgoEnum>(); cmbCompAlg = new EnumDropDown<AlgoEnum>();
StackLayoutForAlgoEnum.Items.Add(new StackLayoutItem(cmbCompAlg, HorizontalAlignment.Stretch, true)); StackLayoutForAlgoEnum.Items.Add(new StackLayoutItem(cmbCompAlg, HorizontalAlignment.Stretch, true));
@@ -56,7 +57,9 @@ namespace apprepodbmgr.Eto
spClamdPort.Value = 3310; spClamdPort.Value = 3310;
chkAntivirus.Checked = Settings.Current.UseAntivirus; chkAntivirus.Checked = Settings.Current.UseAntivirus;
frmClamd.Visible = chkAntivirus.Checked.Value; frmClamd.Visible = chkAntivirus.Checked.Value;
if(Settings.Current.UseAntivirus && Settings.Current.UseClamd)
if(Settings.Current.UseAntivirus &&
Settings.Current.UseClamd)
{ {
chkClamd.Checked = Settings.Current.UseClamd; chkClamd.Checked = Settings.Current.UseClamd;
txtClamdHost.Text = Settings.Current.ClamdHost; txtClamdHost.Text = Settings.Current.ClamdHost;
@@ -64,7 +67,9 @@ namespace apprepodbmgr.Eto
chkClamdIsLocal.Checked = Settings.Current.ClamdIsLocal; 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.Checked = true;
chkVirusTotal.Enabled = true; chkVirusTotal.Enabled = true;
@@ -73,10 +78,7 @@ namespace apprepodbmgr.Eto
btnVirusTotal.Enabled = true; btnVirusTotal.Enabled = true;
} }
protected void OnBtnCancelClicked(object sender, EventArgs e) protected void OnBtnCancelClicked(object sender, EventArgs e) => Close();
{
Close();
}
protected void OnBtnApplyClicked(object sender, EventArgs e) protected void OnBtnApplyClicked(object sender, EventArgs e)
{ {
@@ -86,7 +88,9 @@ namespace apprepodbmgr.Eto
Settings.Current.DatabasePath = txtDatabase.Text; Settings.Current.DatabasePath = txtDatabase.Text;
Settings.Current.RepositoryPath = txtRepository.Text; Settings.Current.RepositoryPath = txtRepository.Text;
Settings.Current.CompressionAlgorithm = cmbCompAlg.SelectedValue; 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.UseClamd = false;
Settings.Current.ClamdHost = null; Settings.Current.ClamdHost = null;
@@ -94,7 +98,8 @@ namespace apprepodbmgr.Eto
Settings.Current.ClamdIsLocal = false; Settings.Current.ClamdIsLocal = false;
} }
if(chkVirusTotal.Checked.Value && chkAntivirus.Checked.Value) if(chkVirusTotal.Checked.Value &&
chkAntivirus.Checked.Value)
{ {
Settings.Current.UseVirusTotal = true; Settings.Current.UseVirusTotal = true;
Settings.Current.VirusTotalKey = txtVirusTotal.Text; Settings.Current.VirusTotalKey = txtVirusTotal.Text;
@@ -117,11 +122,17 @@ namespace apprepodbmgr.Eto
protected void OnBtnUnarClicked(object sender, EventArgs e) 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))) if(!string.IsNullOrWhiteSpace(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)))
dlgFile.Directory = new Uri(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; txtUnar.Text = dlgFile.FileName;
lblUnarVersion.Visible = false; lblUnarVersion.Visible = false;
@@ -130,23 +141,31 @@ namespace apprepodbmgr.Eto
protected void OnBtnTmpClicked(object sender, EventArgs e) protected void OnBtnTmpClicked(object sender, EventArgs e)
{ {
SelectFolderDialog dlgFolder = var dlgFolder = new SelectFolderDialog
new SelectFolderDialog {Title = "Choose temporary folder", Directory = Path.GetTempPath()}; {
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) protected void OnBtnRepositoryClicked(object sender, EventArgs e)
{ {
SelectFolderDialog dlgFolder = var dlgFolder = new SelectFolderDialog
new SelectFolderDialog {Title = "Choose repository folder", Directory = Path.GetTempPath()}; {
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) protected void OnBtnDatabaseClicked(object sender, EventArgs e)
{ {
SaveFileDialog dlgFile = new SaveFileDialog var dlgFile = new SaveFileDialog
{ {
Title = "Choose database to open/create", Title = "Choose database to open/create",
Directory = new Uri(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)), Directory = new Uri(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)),
@@ -154,20 +173,28 @@ namespace apprepodbmgr.Eto
FileName = "apprepodbmgr.db" FileName = "apprepodbmgr.db"
}; };
if(dlgFile.ShowDialog(this) != DialogResult.Ok) return; if(dlgFile.ShowDialog(this) != DialogResult.Ok)
return;
if(File.Exists(dlgFile.FileName)) if(File.Exists(dlgFile.FileName))
{ {
DbCore dbCore = new SQLite(); DbCore dbCore = new SQLite();
bool notDb = false; bool notDb = false;
try { notDb |= !dbCore.OpenDb(dlgFile.FileName, null, null, null); } try
catch { notDb = true; } {
notDb |= !dbCore.OpenDb(dlgFile.FileName, null, null, null);
}
catch
{
notDb = true;
}
if(notDb) if(notDb)
{ {
MessageBox.Show("Cannot open specified file as a database, please choose another.", MessageBox.Show("Cannot open specified file as a database, please choose another.",
MessageBoxType.Error); MessageBoxType.Error);
return; return;
} }
@@ -178,13 +205,20 @@ namespace apprepodbmgr.Eto
DbCore dbCore = new SQLite(); DbCore dbCore = new SQLite();
bool notDb = false; bool notDb = false;
try { notDb |= !dbCore.CreateDb(dlgFile.FileName, null, null, null); } try
catch { notDb = true; } {
notDb |= !dbCore.CreateDb(dlgFile.FileName, null, null, null);
}
catch
{
notDb = true;
}
if(notDb) if(notDb)
{ {
MessageBox.Show("Cannot create a database in the specified file as a database.", MessageBox.Show("Cannot create a database in the specified file as a database.",
MessageBoxType.Error); MessageBoxType.Error);
return; return;
} }
@@ -201,13 +235,11 @@ namespace apprepodbmgr.Eto
oldUnarPath = Settings.Current.UnArchiverPath; oldUnarPath = Settings.Current.UnArchiverPath;
Settings.Current.UnArchiverPath = txtUnar.Text; Settings.Current.UnArchiverPath = txtUnar.Text;
Thread thdCheckUnar = new Thread(Workers.CheckUnar); var thdCheckUnar = new Thread(Workers.CheckUnar);
thdCheckUnar.Start(); thdCheckUnar.Start();
} }
void CheckUnarFinished(string text) void CheckUnarFinished(string text) => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
Workers.FinishedWithText -= CheckUnarFinished; Workers.FinishedWithText -= CheckUnarFinished;
Workers.Failed -= CheckUnarFailed; Workers.Failed -= CheckUnarFailed;
@@ -216,11 +248,8 @@ namespace apprepodbmgr.Eto
lblUnarVersion.Visible = true; lblUnarVersion.Visible = true;
Settings.Current.UnArchiverPath = oldUnarPath; Settings.Current.UnArchiverPath = oldUnarPath;
}); });
}
void CheckUnarFailed(string text) void CheckUnarFailed(string text) => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
Workers.FinishedWithText -= CheckUnarFinished; Workers.FinishedWithText -= CheckUnarFinished;
Workers.Failed -= CheckUnarFailed; Workers.Failed -= CheckUnarFailed;
@@ -229,7 +258,6 @@ namespace apprepodbmgr.Eto
Settings.Current.UnArchiverPath = oldUnarPath; Settings.Current.UnArchiverPath = oldUnarPath;
MessageBox.Show(text, MessageBoxType.Error); MessageBox.Show(text, MessageBoxType.Error);
}); });
}
protected void OnChkAntivirusToggled(object sender, EventArgs e) protected void OnChkAntivirusToggled(object sender, EventArgs e)
{ {
@@ -253,6 +281,7 @@ namespace apprepodbmgr.Eto
if(string.IsNullOrEmpty(txtClamdHost.Text)) if(string.IsNullOrEmpty(txtClamdHost.Text))
{ {
MessageBox.Show("clamd host cannot be empty", MessageBoxType.Error); MessageBox.Show("clamd host cannot be empty", MessageBoxType.Error);
return; return;
} }
@@ -272,6 +301,7 @@ namespace apprepodbmgr.Eto
if(string.IsNullOrEmpty(Context.ClamdVersion)) if(string.IsNullOrEmpty(Context.ClamdVersion))
{ {
MessageBox.Show("Cannot connect to clamd", MessageBoxType.Error); MessageBox.Show("Cannot connect to clamd", MessageBoxType.Error);
return; return;
} }
@@ -290,16 +320,15 @@ namespace apprepodbmgr.Eto
protected void OnBtnVirusTotalClicked(object sender, EventArgs e) protected void OnBtnVirusTotalClicked(object sender, EventArgs e)
{ {
Workers.Failed += VirusTotalTestFailed; Workers.Failed += VirusTotalTestFailed;
if(!Workers.TestVirusTotal(txtVirusTotal.Text)) return;
if(!Workers.TestVirusTotal(txtVirusTotal.Text))
return;
lblVirusTotal.Visible = true; lblVirusTotal.Visible = true;
lblVirusTotal.Text = "Working!"; lblVirusTotal.Text = "Working!";
} }
static void VirusTotalTestFailed(string text) static void VirusTotalTestFailed(string text) => MessageBox.Show(text, MessageBoxType.Error);
{
MessageBox.Show(text, MessageBoxType.Error);
}
#region XAML UI elements #region XAML UI elements
#pragma warning disable 0649 #pragma warning disable 0649
@@ -308,7 +337,7 @@ namespace apprepodbmgr.Eto
TextBox txtDatabase; TextBox txtDatabase;
TextBox txtRepository; TextBox txtRepository;
Label lblUnarVersion; Label lblUnarVersion;
EnumDropDown<AlgoEnum> cmbCompAlg; readonly EnumDropDown<AlgoEnum> cmbCompAlg;
StackLayout StackLayoutForAlgoEnum; StackLayout StackLayoutForAlgoEnum;
GroupBox frmClamd; GroupBox frmClamd;
CheckBox chkAntivirus; CheckBox chkAntivirus;

View File

@@ -41,7 +41,7 @@ namespace apprepodbmgr.Eto
{ {
int infectedFiles; int infectedFiles;
ObservableCollection<DBEntryForEto> lstApps; readonly ObservableCollection<DBEntryForEto> lstApps;
ObservableCollection<DbFile> lstFiles; ObservableCollection<DbFile> lstFiles;
DbFile outIter; DbFile outIter;
bool populatingFiles; bool populatingFiles;
@@ -62,74 +62,130 @@ namespace apprepodbmgr.Eto
lstApps = new ObservableCollection<DBEntryForEto>(); lstApps = new ObservableCollection<DBEntryForEto>();
treeApps.DataStore = lstApps; treeApps.DataStore = lstApps;
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell {Binding = Binding.Property<DBEntryForEto, string>(r => r.developer)}, DataCell = new TextBoxCell
{
Binding = Binding.Property<DBEntryForEto, string>(r => r.developer)
},
HeaderText = "Developer" HeaderText = "Developer"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell {Binding = Binding.Property<DBEntryForEto, string>(r => r.product)}, DataCell = new TextBoxCell
{
Binding = Binding.Property<DBEntryForEto, string>(r => r.product)
},
HeaderText = "Product" HeaderText = "Product"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell {Binding = Binding.Property<DBEntryForEto, string>(r => r.version)}, DataCell = new TextBoxCell
{
Binding = Binding.Property<DBEntryForEto, string>(r => r.version)
},
HeaderText = "Version" HeaderText = "Version"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell {Binding = Binding.Property<DBEntryForEto, string>(r => r.languages)}, DataCell = new TextBoxCell
{
Binding = Binding.Property<DBEntryForEto, string>(r => r.languages)
},
HeaderText = "Languages" HeaderText = "Languages"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell {Binding = Binding.Property<DBEntryForEto, string>(r => r.architecture)}, DataCell = new TextBoxCell
{
Binding = Binding.Property<DBEntryForEto, string>(r => r.architecture)
},
HeaderText = "Architecture" HeaderText = "Architecture"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell {Binding = Binding.Property<DBEntryForEto, string>(r => r.targetos)}, DataCell = new TextBoxCell
{
Binding = Binding.Property<DBEntryForEto, string>(r => r.targetos)
},
HeaderText = "Target OS" HeaderText = "Target OS"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell {Binding = Binding.Property<DBEntryForEto, string>(r => r.format)}, DataCell = new TextBoxCell
{
Binding = Binding.Property<DBEntryForEto, string>(r => r.format)
},
HeaderText = "Format" HeaderText = "Format"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell {Binding = Binding.Property<DBEntryForEto, string>(r => r.description)}, DataCell = new TextBoxCell
{
Binding = Binding.Property<DBEntryForEto, string>(r => r.description)
},
HeaderText = "Description" HeaderText = "Description"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new CheckBoxCell {Binding = Binding.Property<DBEntryForEto, bool?>(r => r.oem)}, DataCell = new CheckBoxCell
{
Binding = Binding.Property<DBEntryForEto, bool?>(r => r.oem)
},
HeaderText = "OEM?" HeaderText = "OEM?"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new CheckBoxCell {Binding = Binding.Property<DBEntryForEto, bool?>(r => r.upgrade)}, DataCell = new CheckBoxCell
{
Binding = Binding.Property<DBEntryForEto, bool?>(r => r.upgrade)
},
HeaderText = "Upgrade?" HeaderText = "Upgrade?"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new CheckBoxCell {Binding = Binding.Property<DBEntryForEto, bool?>(r => r.update)}, DataCell = new CheckBoxCell
{
Binding = Binding.Property<DBEntryForEto, bool?>(r => r.update)
},
HeaderText = "Update?" HeaderText = "Update?"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new CheckBoxCell {Binding = Binding.Property<DBEntryForEto, bool?>(r => r.source)}, DataCell = new CheckBoxCell
{
Binding = Binding.Property<DBEntryForEto, bool?>(r => r.source)
},
HeaderText = "Source?" HeaderText = "Source?"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new CheckBoxCell {Binding = Binding.Property<DBEntryForEto, bool?>(r => r.files)}, DataCell = new CheckBoxCell
{
Binding = Binding.Property<DBEntryForEto, bool?>(r => r.files)
},
HeaderText = "Files?" HeaderText = "Files?"
}); });
treeApps.Columns.Add(new GridColumn treeApps.Columns.Add(new GridColumn
{ {
DataCell = new CheckBoxCell {Binding = Binding.Property<DBEntryForEto, bool?>(r => r.Installer)}, DataCell = new CheckBoxCell
{
Binding = Binding.Property<DBEntryForEto, bool?>(r => r.Installer)
},
HeaderText = "Installer?" HeaderText = "Installer?"
}); });
@@ -138,11 +194,16 @@ namespace apprepodbmgr.Eto
lstFiles = new ObservableCollection<DbFile>(); lstFiles = new ObservableCollection<DbFile>();
treeFiles.DataStore = lstFiles; treeFiles.DataStore = lstFiles;
treeFiles.Columns.Add(new GridColumn treeFiles.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell {Binding = Binding.Property<DbFile, string>(r => r.Sha256)}, DataCell = new TextBoxCell
{
Binding = Binding.Property<DbFile, string>(r => r.Sha256)
},
HeaderText = "SHA256" HeaderText = "SHA256"
}); });
treeFiles.Columns.Add(new GridColumn treeFiles.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell DataCell = new TextBoxCell
@@ -151,34 +212,45 @@ namespace apprepodbmgr.Eto
}, },
HeaderText = "Length" HeaderText = "Length"
}); });
treeFiles.Columns.Add(new GridColumn treeFiles.Columns.Add(new GridColumn
{ {
DataCell = new CheckBoxCell {Binding = Binding.Property<DbFile, bool?>(r => r.Crack)}, DataCell = new CheckBoxCell
{
Binding = Binding.Property<DbFile, bool?>(r => r.Crack)
},
HeaderText = "Crack?" HeaderText = "Crack?"
}); });
treeFiles.Columns.Add(new GridColumn treeFiles.Columns.Add(new GridColumn
{ {
DataCell = new CheckBoxCell {Binding = Binding.Property<DbFile, bool?>(r => r.HasVirus)}, DataCell = new CheckBoxCell
{
Binding = Binding.Property<DbFile, bool?>(r => r.HasVirus)
},
HeaderText = "Has virus?" HeaderText = "Has virus?"
}); });
treeFiles.Columns.Add(new GridColumn treeFiles.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell DataCell = new TextBoxCell
{ {
Binding = Binding.Property<DbFile, DateTime?>(r => r.ClamTime) Binding = Binding.Property<DbFile, DateTime?>(r => r.ClamTime).
.Convert(s => s == null ? "Never" : s.Value.ToString()) Convert(s => s == null ? "Never" : s.Value.ToString())
}, },
HeaderText = "Last scanned with clamd" HeaderText = "Last scanned with clamd"
}); });
treeFiles.Columns.Add(new GridColumn treeFiles.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell DataCell = new TextBoxCell
{ {
Binding = Binding.Property<DbFile, DateTime?>(r => r.VirusTotalTime) Binding = Binding.Property<DbFile, DateTime?>(r => r.VirusTotalTime).
.Convert(s => s == null ? "Never" : s.Value.ToString()) Convert(s => s == null ? "Never" : s.Value.ToString())
}, },
HeaderText = "Last checked on VirusTotal" HeaderText = "Last checked on VirusTotal"
}); });
treeFiles.Columns.Add(new GridColumn treeFiles.Columns.Add(new GridColumn
{ {
DataCell = new TextBoxCell DataCell = new TextBoxCell
@@ -189,11 +261,13 @@ namespace apprepodbmgr.Eto
}); });
treeFiles.AllowMultipleSelection = false; treeFiles.AllowMultipleSelection = false;
treeFiles.CellFormatting += (sender, e) => treeFiles.CellFormatting += (sender, e) =>
{ {
if(((DbFile)e.Item).HasVirus.HasValue) if(((DbFile)e.Item).HasVirus.HasValue)
e.BackgroundColor = ((DbFile)e.Item).HasVirus.Value ? Colors.Red : Colors.Green; e.BackgroundColor = ((DbFile)e.Item).HasVirus.Value ? Colors.Red : Colors.Green;
else e.BackgroundColor = Colors.Yellow; else
e.BackgroundColor = Colors.Yellow;
e.ForegroundColor = Colors.Black; e.ForegroundColor = Colors.Black;
}; };
@@ -216,12 +290,11 @@ namespace apprepodbmgr.Eto
thdPopulateApps.Start(); thdPopulateApps.Start();
} }
void LoadAppsFailed(string text) void LoadAppsFailed(string text) => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
MessageBox.Show($"Error {text} when populating applications, exiting...", MessageBoxButtons.OK, MessageBox.Show($"Error {text} when populating applications, exiting...", MessageBoxButtons.OK,
MessageBoxType.Error, MessageBoxDefaultButton.OK); MessageBoxType.Error, MessageBoxDefaultButton.OK);
if(thdPopulateApps != null) if(thdPopulateApps != null)
{ {
thdPopulateApps.Abort(); thdPopulateApps.Abort();
@@ -233,16 +306,14 @@ namespace apprepodbmgr.Eto
Workers.UpdateProgress -= UpdateProgress; Workers.UpdateProgress -= UpdateProgress;
Application.Instance.Quit(); Application.Instance.Quit();
}); });
}
void LoadAppsFinished() void LoadAppsFinished() => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
Workers.Failed -= LoadAppsFailed; Workers.Failed -= LoadAppsFailed;
Workers.Finished -= LoadAppsFinished; Workers.Finished -= LoadAppsFinished;
Workers.UpdateProgress -= UpdateProgress; Workers.UpdateProgress -= UpdateProgress;
Workers.AddApp -= AddApp; Workers.AddApp -= AddApp;
if(thdPopulateApps != null) if(thdPopulateApps != null)
{ {
thdPopulateApps.Abort(); thdPopulateApps.Abort();
@@ -260,19 +331,23 @@ namespace apprepodbmgr.Eto
lblAppStatus.Visible = true; lblAppStatus.Visible = true;
lblAppStatus.Text = $"{lstApps.Count} applications"; lblAppStatus.Text = $"{lstApps.Count} applications";
}); });
}
void UpdateProgress(string text, string inner, long current, long maximum) void UpdateProgress(string text, string inner, long current, long maximum) =>
{
Application.Instance.Invoke(delegate Application.Instance.Invoke(delegate
{ {
if(!string.IsNullOrWhiteSpace(text) && !string.IsNullOrWhiteSpace(inner)) if(!string.IsNullOrWhiteSpace(text) &&
!string.IsNullOrWhiteSpace(inner))
lblProgress.Text = $"{text}: {inner}"; lblProgress.Text = $"{text}: {inner}";
else if(!string.IsNullOrWhiteSpace(inner)) lblProgress.Text = inner; else if(!string.IsNullOrWhiteSpace(inner))
else lblProgress.Text = text; lblProgress.Text = inner;
else
lblProgress.Text = text;
if(maximum > 0) if(maximum > 0)
{ {
if(current < int.MinValue || current > int.MaxValue || maximum < int.MinValue || if(current < int.MinValue ||
current > int.MaxValue ||
maximum < int.MinValue ||
maximum > int.MaxValue) maximum > int.MaxValue)
{ {
current /= 100; current /= 100;
@@ -284,21 +359,26 @@ namespace apprepodbmgr.Eto
prgProgress.MaxValue = (int)maximum; prgProgress.MaxValue = (int)maximum;
prgProgress.Value = (int)current; prgProgress.Value = (int)current;
} }
else prgProgress.Indeterminate = true; else
prgProgress.Indeterminate = true;
}); });
}
void UpdateProgress2(string text, string inner, long current, long maximum) void UpdateProgress2(string text, string inner, long current, long maximum) =>
{
Application.Instance.Invoke(delegate Application.Instance.Invoke(delegate
{ {
if(!string.IsNullOrWhiteSpace(text) && !string.IsNullOrWhiteSpace(inner)) if(!string.IsNullOrWhiteSpace(text) &&
!string.IsNullOrWhiteSpace(inner))
lblProgress2.Text = $"{text}: {inner}"; lblProgress2.Text = $"{text}: {inner}";
else if(!string.IsNullOrWhiteSpace(inner)) lblProgress2.Text = inner; else if(!string.IsNullOrWhiteSpace(inner))
else lblProgress2.Text = text; lblProgress2.Text = inner;
else
lblProgress2.Text = text;
if(maximum > 0) if(maximum > 0)
{ {
if(current < int.MinValue || current > int.MaxValue || maximum < int.MinValue || if(current < int.MinValue ||
current > int.MaxValue ||
maximum < int.MinValue ||
maximum > int.MaxValue) maximum > int.MaxValue)
{ {
current /= 100; current /= 100;
@@ -310,27 +390,35 @@ namespace apprepodbmgr.Eto
prgProgress2.MaxValue = (int)maximum; prgProgress2.MaxValue = (int)maximum;
prgProgress2.Value = (int)current; prgProgress2.Value = (int)current;
} }
else prgProgress2.Indeterminate = true; else
prgProgress2.Indeterminate = true;
}); });
}
void AddApp(DbEntry app) void AddApp(DbEntry app) => Application.Instance.Invoke(delegate
{ {
Application.Instance.Invoke(delegate { lstApps.Add(new DBEntryForEto(app)); }); lstApps.Add(new DBEntryForEto(app));
} });
protected void OnBtnAddClicked(object sender, EventArgs e) protected void OnBtnAddClicked(object sender, EventArgs e)
{ {
dlgAdd dlgAdd = new dlgAdd(); var dlgAdd = new dlgAdd();
dlgAdd.OnAddedApp += app => { lstApps.Add(new DBEntryForEto(app)); };
dlgAdd.OnAddedApp += app =>
{
lstApps.Add(new DBEntryForEto(app));
};
dlgAdd.ShowModal(this); dlgAdd.ShowModal(this);
} }
protected void OnBtnRemoveClicked(object sender, EventArgs e) protected void OnBtnRemoveClicked(object sender, EventArgs e)
{ {
if(treeApps.SelectedItem == null) return; if(treeApps.SelectedItem == null)
return;
if(MessageBox.Show("Are you sure you want to remove the selected application?", MessageBoxButtons.YesNo, if(MessageBox.Show("Are you sure you want to remove the selected application?", MessageBoxButtons.YesNo,
MessageBoxType.Question, MessageBoxDefaultButton.No) != DialogResult.Yes) return; MessageBoxType.Question, MessageBoxDefaultButton.No) != DialogResult.Yes)
return;
Workers.RemoveApp(((DBEntryForEto)treeApps.SelectedItem).id, ((DBEntryForEto)treeApps.SelectedItem).mdid); Workers.RemoveApp(((DBEntryForEto)treeApps.SelectedItem).id, ((DBEntryForEto)treeApps.SelectedItem).mdid);
lstApps.Remove((DBEntryForEto)treeApps.SelectedItem); lstApps.Remove((DBEntryForEto)treeApps.SelectedItem);
@@ -338,10 +426,16 @@ namespace apprepodbmgr.Eto
protected void OnBtnSaveClicked(object sender, EventArgs e) protected void OnBtnSaveClicked(object sender, EventArgs e)
{ {
if(treeApps.SelectedItem == null) return; if(treeApps.SelectedItem == null)
return;
SelectFolderDialog dlgFolder = new SelectFolderDialog {Title = "Save to..."}; var dlgFolder = new SelectFolderDialog
if(dlgFolder.ShowDialog(this) != DialogResult.Ok) return; {
Title = "Save to..."
};
if(dlgFolder.ShowDialog(this) != DialogResult.Ok)
return;
Context.DbInfo.Id = ((DBEntryForEto)treeApps.SelectedItem).id; Context.DbInfo.Id = ((DBEntryForEto)treeApps.SelectedItem).id;
Context.Path = dlgFolder.Directory; Context.Path = dlgFolder.Directory;
@@ -366,9 +460,7 @@ namespace apprepodbmgr.Eto
thdSaveAs.Start(); thdSaveAs.Start();
} }
void SaveAsFailed(string text) void SaveAsFailed(string text) => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
MessageBox.Show(text, MessageBoxButtons.OK, MessageBoxType.Error); MessageBox.Show(text, MessageBoxButtons.OK, MessageBoxType.Error);
@@ -397,11 +489,8 @@ namespace apprepodbmgr.Eto
Context.Path = null; Context.Path = null;
}); });
}
void SaveAsFinished() void SaveAsFinished() => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
lblProgress.Visible = false; lblProgress.Visible = false;
prgProgress.Visible = false; prgProgress.Visible = false;
@@ -429,11 +518,10 @@ namespace apprepodbmgr.Eto
Context.Path = null; Context.Path = null;
}); });
}
protected void OnBtnSettingsClicked(object sender, EventArgs e) protected void OnBtnSettingsClicked(object sender, EventArgs e)
{ {
dlgSettings _dlgSettings = new dlgSettings(); var _dlgSettings = new dlgSettings();
_dlgSettings.ShowModal(); _dlgSettings.ShowModal();
} }
@@ -467,24 +555,27 @@ namespace apprepodbmgr.Eto
thdPopulateApps = null; thdPopulateApps = null;
} }
if(thdSaveAs == null) return; if(thdSaveAs == null)
return;
thdSaveAs.Abort(); thdSaveAs.Abort();
thdSaveAs = null; thdSaveAs = null;
} }
protected void OnDeleteEvent(object sender, EventArgs e) protected void OnDeleteEvent(object sender, EventArgs e) => OnBtnStopClicked(sender, e);
{
OnBtnStopClicked(sender, e);
}
protected void OnBtnCompressClicked(object sender, EventArgs e) protected void OnBtnCompressClicked(object sender, EventArgs e)
{ {
if(treeApps.SelectedItem == null) return; if(treeApps.SelectedItem == null)
return;
SaveFileDialog dlgFile = new SaveFileDialog {Title = "Compress to..."}; var dlgFile = new SaveFileDialog
{
Title = "Compress to..."
};
if(dlgFile.ShowDialog(this) != DialogResult.Ok) return; if(dlgFile.ShowDialog(this) != DialogResult.Ok)
return;
Context.DbInfo.Id = ((DBEntryForEto)treeApps.SelectedItem).id; Context.DbInfo.Id = ((DBEntryForEto)treeApps.SelectedItem).id;
Context.Path = dlgFile.FileName; Context.Path = dlgFile.FileName;
@@ -509,9 +600,7 @@ namespace apprepodbmgr.Eto
thdCompressTo.Start(); thdCompressTo.Start();
} }
void CompressToFailed(string text) void CompressToFailed(string text) => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
MessageBox.Show(text, MessageBoxButtons.OK, MessageBoxType.Error); MessageBox.Show(text, MessageBoxButtons.OK, MessageBoxType.Error);
lblProgress.Visible = false; lblProgress.Visible = false;
@@ -539,11 +628,8 @@ namespace apprepodbmgr.Eto
Context.Path = null; Context.Path = null;
}); });
}
void CompressToFinished() void CompressToFinished() => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
lblProgress.Visible = false; lblProgress.Visible = false;
lblProgress2.Visible = false; lblProgress2.Visible = false;
@@ -572,7 +658,6 @@ namespace apprepodbmgr.Eto
Context.Path = null; Context.Path = null;
}); });
}
protected void OnBtnStopFilesClicked(object sender, EventArgs e) protected void OnBtnStopFilesClicked(object sender, EventArgs e)
{ {
@@ -607,9 +692,10 @@ namespace apprepodbmgr.Eto
protected void OnBtnToggleCrackClicked(object sender, EventArgs e) protected void OnBtnToggleCrackClicked(object sender, EventArgs e)
{ {
if(treeFiles.SelectedItem == null) return; if(treeFiles.SelectedItem == null)
return;
DbFile file = (DbFile)treeFiles.SelectedItem; var file = (DbFile)treeFiles.SelectedItem;
bool crack = !file.Crack; bool crack = !file.Crack;
Workers.ToggleCrack(file.Sha256, crack); Workers.ToggleCrack(file.Sha256, crack);
@@ -621,7 +707,8 @@ namespace apprepodbmgr.Eto
protected void OnBtnScanWithClamdClicked(object sender, EventArgs e) protected void OnBtnScanWithClamdClicked(object sender, EventArgs e)
{ {
if(treeFiles.SelectedItem == null) return; if(treeFiles.SelectedItem == null)
return;
DbFile file = Workers.GetDBFile(((DbFile)treeFiles.SelectedItem).Sha256); DbFile file = Workers.GetDBFile(((DbFile)treeFiles.SelectedItem).Sha256);
outIter = (DbFile)treeFiles.SelectedItem; outIter = (DbFile)treeFiles.SelectedItem;
@@ -629,6 +716,7 @@ namespace apprepodbmgr.Eto
if(file == null) if(file == null)
{ {
MessageBox.Show("Cannot get file from database", MessageBoxType.Error); MessageBox.Show("Cannot get file from database", MessageBoxType.Error);
return; return;
} }
@@ -649,9 +737,7 @@ namespace apprepodbmgr.Eto
thdScanFile.Start(); thdScanFile.Start();
} }
void ClamdFailed(string text) void ClamdFailed(string text) => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
treeFiles.Enabled = true; treeFiles.Enabled = true;
btnToggleCrack.Enabled = true; btnToggleCrack.Enabled = true;
@@ -663,16 +749,15 @@ namespace apprepodbmgr.Eto
Workers.ScanFinished -= ClamdFinished; Workers.ScanFinished -= ClamdFinished;
Workers.UpdateProgress -= UpdateVirusProgress; Workers.UpdateProgress -= UpdateVirusProgress;
lblProgressFiles1.Text = ""; lblProgressFiles1.Text = "";
if(thdScanFile == null) return;
if(thdScanFile == null)
return;
thdScanFile.Abort(); thdScanFile.Abort();
thdScanFile = null; thdScanFile = null;
}); });
}
void ClamdFinished(DbFile file) void ClamdFinished(DbFile file) => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
treeFiles.Enabled = true; treeFiles.Enabled = true;
btnToggleCrack.Enabled = true; btnToggleCrack.Enabled = true;
@@ -684,22 +769,25 @@ namespace apprepodbmgr.Eto
lblProgressFiles1.Text = ""; lblProgressFiles1.Text = "";
prgProgressFiles1.Visible = false; prgProgressFiles1.Visible = false;
lblProgressFiles1.Visible = false; lblProgressFiles1.Visible = false;
if(thdScanFile != null) thdScanFile = null;
if((!outIter.HasVirus.HasValue || outIter.HasVirus.HasValue && !outIter.HasVirus.Value) && if(thdScanFile != null)
thdScanFile = null;
if((!outIter.HasVirus.HasValue || (outIter.HasVirus.HasValue && !outIter.HasVirus.Value)) &&
file.HasVirus.HasValue && file.HasVirus.HasValue &&
file.HasVirus.Value) infectedFiles++; file.HasVirus.Value)
infectedFiles++;
lstFiles.Remove(outIter); lstFiles.Remove(outIter);
AddFile(file); AddFile(file);
lblFileStatus.Text = $"{lstFiles.Count} files ({infectedFiles} infected)"; lblFileStatus.Text = $"{lstFiles.Count} files ({infectedFiles} infected)";
}); });
}
protected void OnBtnCheckInVirusTotalClicked(object sender, EventArgs e) protected void OnBtnCheckInVirusTotalClicked(object sender, EventArgs e)
{ {
if(treeFiles.SelectedItem == null) return; if(treeFiles.SelectedItem == null)
return;
DbFile file = Workers.GetDBFile(((DbFile)treeFiles.SelectedItem).Sha256); DbFile file = Workers.GetDBFile(((DbFile)treeFiles.SelectedItem).Sha256);
outIter = (DbFile)treeFiles.SelectedItem; outIter = (DbFile)treeFiles.SelectedItem;
@@ -707,6 +795,7 @@ namespace apprepodbmgr.Eto
if(file == null) if(file == null)
{ {
MessageBox.Show("Cannot get file from database", MessageBoxType.Error); MessageBox.Show("Cannot get file from database", MessageBoxType.Error);
return; return;
} }
@@ -727,9 +816,7 @@ namespace apprepodbmgr.Eto
thdScanFile.Start(); thdScanFile.Start();
} }
void VirusTotalFailed(string text) void VirusTotalFailed(string text) => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
treeFiles.Enabled = true; treeFiles.Enabled = true;
btnToggleCrack.Enabled = true; btnToggleCrack.Enabled = true;
@@ -740,14 +827,14 @@ namespace apprepodbmgr.Eto
Workers.ScanFinished -= VirusTotalFinished; Workers.ScanFinished -= VirusTotalFinished;
Workers.UpdateProgress -= UpdateVirusProgress; Workers.UpdateProgress -= UpdateVirusProgress;
lblProgressFiles1.Text = ""; lblProgressFiles1.Text = "";
if(thdScanFile != null) thdScanFile = null;
if(thdScanFile != null)
thdScanFile = null;
MessageBox.Show(text, MessageBoxType.Error); MessageBox.Show(text, MessageBoxType.Error);
}); });
}
void VirusTotalFinished(DbFile file) void VirusTotalFinished(DbFile file) => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
treeFiles.Enabled = true; treeFiles.Enabled = true;
btnToggleCrack.Enabled = true; btnToggleCrack.Enabled = true;
@@ -758,23 +845,26 @@ namespace apprepodbmgr.Eto
Workers.UpdateProgress -= UpdateVirusProgress; Workers.UpdateProgress -= UpdateVirusProgress;
lblProgressFiles1.Text = ""; lblProgressFiles1.Text = "";
prgProgressFiles1.Visible = false; prgProgressFiles1.Visible = false;
if(thdScanFile != null) thdScanFile = null;
if((!outIter.HasVirus.HasValue || outIter.HasVirus.HasValue && !outIter.HasVirus.Value) && if(thdScanFile != null)
thdScanFile = null;
if((!outIter.HasVirus.HasValue || (outIter.HasVirus.HasValue && !outIter.HasVirus.Value)) &&
file.HasVirus.HasValue && file.HasVirus.HasValue &&
file.HasVirus.Value) infectedFiles++; file.HasVirus.Value)
infectedFiles++;
lstFiles.Remove(outIter); lstFiles.Remove(outIter);
AddFile(file); AddFile(file);
lblFileStatus.Text = $"{lstFiles.Count} files ({infectedFiles} infected)"; lblFileStatus.Text = $"{lstFiles.Count} files ({infectedFiles} infected)";
}); });
}
void UpdateVirusProgress(string text, string inner, long current, long maximum) void UpdateVirusProgress(string text, string inner, long current, long maximum) =>
Application.Instance.Invoke(delegate
{ {
Application.Instance.Invoke(delegate { lblProgressFiles1.Text = text; }); lblProgressFiles1.Text = text;
} });
protected void OnBtnPopulateFilesClicked(object sender, EventArgs e) protected void OnBtnPopulateFilesClicked(object sender, EventArgs e)
{ {
@@ -798,17 +888,22 @@ namespace apprepodbmgr.Eto
thdPopulateFiles.Start(); thdPopulateFiles.Start();
} }
void UpdateFileProgress(string text, string inner, long current, long maximum) void UpdateFileProgress(string text, string inner, long current, long maximum) =>
{
Application.Instance.Invoke(delegate Application.Instance.Invoke(delegate
{ {
if(!string.IsNullOrWhiteSpace(text) && !string.IsNullOrWhiteSpace(inner)) if(!string.IsNullOrWhiteSpace(text) &&
!string.IsNullOrWhiteSpace(inner))
lblProgressFiles1.Text = $"{text}: {inner}"; lblProgressFiles1.Text = $"{text}: {inner}";
else if(!string.IsNullOrWhiteSpace(inner)) lblProgressFiles1.Text = inner; else if(!string.IsNullOrWhiteSpace(inner))
else lblProgressFiles1.Text = text; lblProgressFiles1.Text = inner;
else
lblProgressFiles1.Text = text;
if(maximum > 0) if(maximum > 0)
{ {
if(current < int.MinValue || current > int.MaxValue || maximum < int.MinValue || if(current < int.MinValue ||
current > int.MaxValue ||
maximum < int.MinValue ||
maximum > int.MaxValue) maximum > int.MaxValue)
{ {
current /= 100; current /= 100;
@@ -820,21 +915,26 @@ namespace apprepodbmgr.Eto
prgProgressFiles1.MaxValue = (int)maximum; prgProgressFiles1.MaxValue = (int)maximum;
prgProgressFiles1.Value = (int)current; prgProgressFiles1.Value = (int)current;
} }
else prgProgressFiles1.Indeterminate = true; else
prgProgressFiles1.Indeterminate = true;
}); });
}
void UpdateFileProgress2(string text, string inner, long current, long maximum) void UpdateFileProgress2(string text, string inner, long current, long maximum) =>
{
Application.Instance.Invoke(delegate Application.Instance.Invoke(delegate
{ {
if(!string.IsNullOrWhiteSpace(text) && !string.IsNullOrWhiteSpace(inner)) if(!string.IsNullOrWhiteSpace(text) &&
!string.IsNullOrWhiteSpace(inner))
lblProgressFiles2.Text = $"{text}: {inner}"; lblProgressFiles2.Text = $"{text}: {inner}";
else if(!string.IsNullOrWhiteSpace(inner)) lblProgressFiles2.Text = inner; else if(!string.IsNullOrWhiteSpace(inner))
else lblProgressFiles2.Text = text; lblProgressFiles2.Text = inner;
else
lblProgressFiles2.Text = text;
if(maximum > 0) if(maximum > 0)
{ {
if(current < int.MinValue || current > int.MaxValue || maximum < int.MinValue || if(current < int.MinValue ||
current > int.MaxValue ||
maximum < int.MinValue ||
maximum > int.MaxValue) maximum > int.MaxValue)
{ {
current /= 100; current /= 100;
@@ -846,23 +946,20 @@ namespace apprepodbmgr.Eto
prgProgressFiles2.MaxValue = (int)maximum; prgProgressFiles2.MaxValue = (int)maximum;
prgProgressFiles2.Value = (int)current; prgProgressFiles2.Value = (int)current;
} }
else prgProgressFiles2.Indeterminate = true; else
prgProgressFiles2.Indeterminate = true;
}); });
}
void AddFile(DbFile file) void AddFile(DbFile file) => Application.Instance.Invoke(delegate
{ {
Application.Instance.Invoke(delegate if(file.HasVirus.HasValue &&
{ file.HasVirus.Value)
if(file.HasVirus.HasValue && file.HasVirus.Value) infectedFiles++; infectedFiles++;
lstFiles.Add(file); lstFiles.Add(file);
}); });
}
void AddFiles(List<DbFile> files) void AddFiles(List<DbFile> files) => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
List<DbFile> foo = new List<DbFile>(); List<DbFile> foo = new List<DbFile>();
foo.AddRange(lstFiles); foo.AddRange(lstFiles);
@@ -870,19 +967,18 @@ namespace apprepodbmgr.Eto
lstFiles = new ObservableCollection<DbFile>(foo); lstFiles = new ObservableCollection<DbFile>(foo);
foreach(DbFile file in files) foreach(DbFile file in files)
if(file.HasVirus.HasValue && file.HasVirus.Value) if(file.HasVirus.HasValue &&
file.HasVirus.Value)
infectedFiles++; infectedFiles++;
}); });
}
void LoadFilesFailed(string text) void LoadFilesFailed(string text) => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
MessageBox.Show($"Error {text} when populating files, exiting...", MessageBoxType.Error); MessageBox.Show($"Error {text} when populating files, exiting...", MessageBoxType.Error);
Workers.Failed -= LoadFilesFailed; Workers.Failed -= LoadFilesFailed;
Workers.Finished -= LoadFilesFinished; Workers.Finished -= LoadFilesFinished;
Workers.UpdateProgress -= UpdateFileProgress2; Workers.UpdateProgress -= UpdateFileProgress2;
if(thdPopulateFiles != null) if(thdPopulateFiles != null)
{ {
thdPopulateFiles.Abort(); thdPopulateFiles.Abort();
@@ -895,15 +991,13 @@ namespace apprepodbmgr.Eto
btnPopulateFiles.Visible = true; btnPopulateFiles.Visible = true;
populatingFiles = false; populatingFiles = false;
}); });
}
void LoadFilesFinished() void LoadFilesFinished() => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
Workers.Failed -= LoadFilesFailed; Workers.Failed -= LoadFilesFailed;
Workers.Finished -= LoadFilesFinished; Workers.Finished -= LoadFilesFinished;
Workers.UpdateProgress -= UpdateFileProgress2; Workers.UpdateProgress -= UpdateFileProgress2;
if(thdPopulateFiles != null) if(thdPopulateFiles != null)
{ {
thdPopulateFiles.Abort(); thdPopulateFiles.Abort();
@@ -928,11 +1022,11 @@ namespace apprepodbmgr.Eto
lblFileStatus.Visible = true; lblFileStatus.Visible = true;
lblFileStatus.Text = $"{lstFiles.Count} files ({infectedFiles} infected)"; lblFileStatus.Text = $"{lstFiles.Count} files ({infectedFiles} infected)";
}); });
}
void treeFilesSelectionChanged(object sender, EventArgs e) void treeFilesSelectionChanged(object sender, EventArgs e)
{ {
if(treeFiles.SelectedItem == null) return; if(treeFiles.SelectedItem == null)
return;
btnToggleCrack.Text = ((DbFile)treeFiles.SelectedItem).Crack ? "Mark as not crack" : "Mark as crack"; btnToggleCrack.Text = ((DbFile)treeFiles.SelectedItem).Crack ? "Mark as not crack" : "Mark as crack";
} }
@@ -961,9 +1055,7 @@ namespace apprepodbmgr.Eto
thdScanFile.Start(); thdScanFile.Start();
} }
void AllClamdFinished() void AllClamdFinished() => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
treeFiles.Enabled = true; treeFiles.Enabled = true;
btnToggleCrack.Enabled = true; btnToggleCrack.Enabled = true;
@@ -979,23 +1071,27 @@ namespace apprepodbmgr.Eto
prgProgressFiles2.Visible = false; prgProgressFiles2.Visible = false;
btnStopFiles.Visible = false; btnStopFiles.Visible = false;
scanningFiles = false; scanningFiles = false;
if(thdScanFile != null) thdScanFile = null;
if(thdScanFile != null)
thdScanFile = null;
OnBtnPopulateFilesClicked(null, new EventArgs()); OnBtnPopulateFilesClicked(null, new EventArgs());
}); });
}
void UpdateVirusProgress2(string text, string inner, long current, long maximum) void UpdateVirusProgress2(string text, string inner, long current, long maximum) =>
Application.Instance.Invoke(delegate
{ {
Application.Instance.Invoke(delegate { lblProgressFiles2.Text = text; }); lblProgressFiles2.Text = text;
} });
protected void OnBtnCleanFilesClicked(object sender, EventArgs e) protected void OnBtnCleanFilesClicked(object sender, EventArgs e)
{ {
DialogResult result = DialogResult result =
MessageBox.Show("This option will search the database for any known file that doesn't\n" + "belong to any application and remove it from the database.\n\n" + "It will then search the repository for any file not on the database and remove it.\n\n" + "THIS OPERATION MAY VERY LONG, CANNOT BE CANCELED AND REMOVES DATA ON DISK.\n\n" + "Are you sure to continue?", MessageBox.Show("This option will search the database for any known file that doesn't\n" + "belong to any application and remove it from the database.\n\n" + "It will then search the repository for any file not on the database and remove it.\n\n" + "THIS OPERATION MAY VERY LONG, CANNOT BE CANCELED AND REMOVES DATA ON DISK.\n\n" + "Are you sure to continue?",
MessageBoxButtons.YesNo, MessageBoxType.Question); MessageBoxButtons.YesNo, MessageBoxType.Question);
if(result != DialogResult.Yes) return;
if(result != DialogResult.Yes)
return;
btnCleanFiles.Visible = false; btnCleanFiles.Visible = false;
btnToggleCrack.Visible = false; btnToggleCrack.Visible = false;
@@ -1023,9 +1119,7 @@ namespace apprepodbmgr.Eto
thdCleanFiles.Start(); thdCleanFiles.Start();
} }
void CleanFilesFinished() void CleanFilesFinished() => Application.Instance.Invoke(delegate
{
Application.Instance.Invoke(delegate
{ {
btnCleanFiles.Visible = true; btnCleanFiles.Visible = true;
btnToggleCrack.Visible = true; btnToggleCrack.Visible = true;
@@ -1045,11 +1139,12 @@ namespace apprepodbmgr.Eto
mnuCompress.Enabled = true; mnuCompress.Enabled = true;
btnQuit.Enabled = true; btnQuit.Enabled = true;
mnuFile.Enabled = true; mnuFile.Enabled = true;
if(thdCleanFiles != null) thdCleanFiles = null;
if(thdCleanFiles != null)
thdCleanFiles = null;
OnBtnPopulateFilesClicked(null, new EventArgs()); OnBtnPopulateFilesClicked(null, new EventArgs());
}); });
}
#region XAML UI elements #region XAML UI elements
#pragma warning disable 0649 #pragma warning disable 0649

View File

@@ -11,7 +11,7 @@ namespace apprepodbmgr.Eto
{ {
public class pnlDescription : Panel public class pnlDescription : Panel
{ {
ObservableCollection<ListItem> cmbCodepagesItems; readonly ObservableCollection<ListItem> cmbCodepagesItems;
Encoding currentEncoding; Encoding currentEncoding;
public string description; public string description;
@@ -21,31 +21,52 @@ namespace apprepodbmgr.Eto
treeFiles.Columns.Add(new GridColumn 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" HeaderText = "File"
}); });
treeFiles.AllowMultipleSelection = false; treeFiles.AllowMultipleSelection = false;
treeFiles.SelectionChanged += TreeFilesOnSelectionChanged; treeFiles.SelectionChanged += TreeFilesOnSelectionChanged;
cmbCodepagesItems = new ObservableCollection<ListItem>(); cmbCodepagesItems = new ObservableCollection<ListItem>();
foreach(EncodingInfo enc in Claunia.Encoding.Encoding.GetEncodings()) 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()) 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); cmbCodepages.DataStore = cmbCodepagesItems.OrderBy(t => t.Text);
try try
{ {
currentEncoding = Claunia.Encoding.Encoding.GetEncoding("ibm437"); currentEncoding = Claunia.Encoding.Encoding.GetEncoding("ibm437");
cmbCodepages.SelectedKey = currentEncoding.BodyName; cmbCodepages.SelectedKey = currentEncoding.BodyName;
} }
catch { currentEncoding = Encoding.ASCII; } catch
{
currentEncoding = Encoding.ASCII;
}
cmbCodepages.SelectedIndexChanged += CmbCodepagesOnSelectedIndexChanged; cmbCodepages.SelectedIndexChanged += CmbCodepagesOnSelectedIndexChanged;
} }
void CmbCodepagesOnSelectedIndexChanged(object sender, EventArgs eventArgs) void CmbCodepagesOnSelectedIndexChanged(object sender, EventArgs eventArgs)
{ {
try { currentEncoding = Claunia.Encoding.Encoding.GetEncoding(cmbCodepages.SelectedKey); } try
{
currentEncoding = Claunia.Encoding.Encoding.GetEncoding(cmbCodepages.SelectedKey);
}
catch catch
{ {
currentEncoding = Encoding.ASCII; currentEncoding = Encoding.ASCII;
@@ -59,9 +80,11 @@ namespace apprepodbmgr.Eto
{ {
txtDescription.Text = ""; txtDescription.Text = "";
description = null; 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(); description = sr.ReadToEnd();
txtDescription.Text = description; txtDescription.Text = description;
sr.Close(); sr.Close();

View File

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

View File

@@ -19,22 +19,37 @@ namespace apprepodbmgr.Eto
treeArchs.Columns.Add(new GridColumn 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" HeaderText = "Arch"
}); });
treeOs.Columns.Add(new GridColumn 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" HeaderText = "Name"
}); });
treeOs.Columns.Add(new GridColumn 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" HeaderText = "Version"
}); });
treeVersions.Columns.Add(new GridColumn 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" HeaderText = "Version"
}); });
} }