diff --git a/Core/Servicers/Instances/Data.cs b/Core/Servicers/Instances/Data.cs index 8c42ef780e7162859572f4a74d3a355e36dfa64f..8af152c4e85aa13e18910ad1105d63e46cc9cd8f 100644 --- a/Core/Servicers/Instances/Data.cs +++ b/Core/Servicers/Instances/Data.cs @@ -13,6 +13,8 @@ using Npoi.Mapper; using System.IO; using CsvHelper; using System.Globalization; +using System.Threading.Tasks; +using NPOI.SS.Formula.Functions; namespace Core.Servicers.Instances { @@ -26,156 +28,101 @@ namespace Core.Servicers.Instances _appData = appData_; _database = database_; } - public void Set(string processName, int seconds, DateTime? time_ = null) + + public void SaveAppDuration(string processName_, int duration_, DateTime startDateTime_) { - lock (setLock) - { - DateTime time = !time_.HasValue ? DateTime.Now : time_.Value; - var today = time.Date; + // 过滤无效数据 + if (string.IsNullOrEmpty(processName_) || duration_ <= 0) return; - if (string.IsNullOrEmpty(processName) || seconds <= 0) + Task.Run(() => + { + try { - return; - } + if (startDateTime_.Minute == 59 && startDateTime_.Second >= 58) + { + // 当记录开始时间接近59分59秒时划到下一个小时时段 + startDateTime_ = startDateTime_.AddSeconds(2); + startDateTime_ = new DateTime(startDateTime_.Year, startDateTime_.Month, startDateTime_.Day, startDateTime_.Hour, 0, 0); + } - AppModel app = _appData.GetApp(processName); + using (var db = _database.GetWriterContext()) + { + var app = db.App.Where(m => m.Name == processName_).FirstOrDefault(); + if (app == null) + { + _database.CloseWriter(); + return; + } - if (app == null) - { - return; - } - // 统计app累计使用时长 - app.TotalTime += seconds; - _appData.UpdateApp(app); + // 当前时段最大可记录时长 + int nowHoursMaxDuration = (60 - startDateTime_.Minute) * 60; + duration_ = duration_ > nowHoursMaxDuration ? nowHoursMaxDuration : duration_; + // 更新app累计时长 + app.TotalTime += duration_; - //using (var db = _database.GetReaderContext()) - using (var db = _database.GetWriterContext()) - { - using (var transcation = db.Database.BeginTransaction()) - { - try + // 更新每日数据 + var dailyLog = db.DailyLog.SingleOrDefault(m => m.Date == startDateTime_.Date && m.AppModelID == app.ID); + if (dailyLog == null) { - var res = db.DailyLog.SingleOrDefault(m => m.Date == today && m.AppModelID == app.ID); - if (res == null) + //数据库中没有时则创建 + db.DailyLog.Add(new DailyLogModel() { - //数据库中没有时则创建 - db.DailyLog.Add(new Models.DailyLogModel() - { - Date = today, - AppModelID = app.ID, - Time = seconds, - }); + Date = startDateTime_.Date, + AppModelID = app.ID, + Time = duration_ > 86400 ? 86400 : duration_, + }); + } + else + { + if (dailyLog.Time + duration_ > 86400) + { + dailyLog.Time = 86400; } else { - res.Time += seconds; + dailyLog.Time += duration_; } - - db.SaveChanges(); - transcation.Commit(); - } - catch (Exception e) - { - Logger.Error(e.ToString()); - transcation.Rollback(); } - finally - { - _database.CloseWriter(); - } - } - } - - SetHoursTime(app, seconds, time); - } - } - - private void SetHoursTime(AppModel app, int seconds, DateTime time) - { - string processName = app.Name; - // 当前时段 - var nowtime = new DateTime(time.Year, time.Month, time.Day, time.Hour, 0, 0); - - if (time.Minute == 59 && time.Second == 59) - { - SetHoursTime(app, seconds, nowtime.AddHours(1)); - return; - } - - if (seconds <= 0 || time > DateTime.Now) - { - return; - } - - - //using (var db = _database.GetReaderContext()) - using (var db = _database.GetWriterContext()) - { - using (var transcation = db.Database.BeginTransaction()) - { - try - { - var hourslog = db.HoursLog.SingleOrDefault( - m => - m.DataTime == nowtime - && m.AppModelID == app.ID - ); - - int overflowSeconds = 0; - - if (hourslog == null) + // 更新时段数据 + var time = new DateTime(startDateTime_.Year, startDateTime_.Month, startDateTime_.Day, startDateTime_.Hour, 0, 0); + var hoursLog = db.HoursLog.SingleOrDefault(m => m.DataTime == time && m.AppModelID == app.ID); + if (hoursLog == null) { - // 没有时创建 - - if (seconds > 3600) + // 没有记录时创建 + db.HoursLog.Add(new HoursLogModel() { - overflowSeconds = seconds - 3600; - seconds = 3600; - } - - db.HoursLog.Add(new Models.HoursLogModel() - { - DataTime = nowtime, + DataTime = time, AppModelID = app.ID, - Time = seconds + Time = duration_ }); } else { - if (hourslog.Time + seconds > 3600) + if (hoursLog.Time + duration_ > 3600) { - hourslog.Time = 3600; - overflowSeconds = hourslog.Time + seconds - 3600; + hoursLog.Time = 3600; } else { - hourslog.Time += seconds; + hoursLog.Time += duration_; } } db.SaveChanges(); - transcation.Commit(); - - if (overflowSeconds > 0) - { - SetHoursTime(app, overflowSeconds, nowtime.AddHours(1)); - } - } - catch (Exception e) - { - Logger.Error(e.ToString()); - transcation.Rollback(); - } - finally - { _database.CloseWriter(); + Logger.Info($"Save app time done.Process:{processName_},Duration:{duration_},StartDateTime:{startDateTime_},AppID:{app.ID}"); } } - //_database.Close(); - } + catch (Exception e) + { + Logger.Error($"Save app time error!Process:{processName_},Duration:{duration_},StartDateTime:{startDateTime_}.\r\nError:\r\n{e.Message}"); + + } + }); } + public List GetTodaylogList() { diff --git a/Core/Servicers/Instances/Main.cs b/Core/Servicers/Instances/Main.cs index faa61db88df16f4428478622286c4f4c9c5f06da..77536066b302e98c87b840dfc1f29671843f1917 100644 --- a/Core/Servicers/Instances/Main.cs +++ b/Core/Servicers/Instances/Main.cs @@ -9,6 +9,7 @@ using System; using System.Collections.Generic; using System.Data.Entity; using System.Diagnostics; +using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; @@ -148,13 +149,13 @@ namespace Core.Servicers.Instances { await Task.Run(() => { - Debug.WriteLine("db self check start"); + CreateDirectory(); + // 数据库自检 using (var db = new TaiDbContext()) { db.SelfCheck(); } - Debug.WriteLine("db self check over!"); // 加载app信息 appData.Load(); @@ -172,14 +173,14 @@ namespace Core.Servicers.Instances config = appConfig.GetConfig(); UpdateConfigIgnoreProcess(); - + // 启动睡眠监测 sleepdiscover.Start(); - + // 初始化过滤器 _webFilter.Init(); - + // 启动主服务 Start(); @@ -208,6 +209,14 @@ namespace Core.Servicers.Instances appObserver?.Stop(); } + /// + /// 创建程序目录 + /// + private void CreateDirectory() + { + string dir = Path.Combine(FileHelper.GetRootDirectory(), "Data"); + Directory.CreateDirectory(dir); + } private void UpdateConfigIgnoreProcess() { @@ -335,8 +344,12 @@ namespace Core.Servicers.Instances return; } + string lastActiveProcess = activeProcess != null ? activeProcess.ToString() : ""; + bool isCheck = IsCheckApp(args.ProcessName, args.Description, args.File); + Logger.Info($"Active[{isCheck}]:" + args.ProcessName + ",Last:" + lastActiveProcess + ",Time:" + activeStartTime.ToString()); + if (activeProcess != args.ProcessName) { UpdateTime(); @@ -354,41 +367,45 @@ namespace Core.Servicers.Instances { activeProcess = null; } + } - private void HandleLinks(string processName, int seconds, DateTime? time = null) + private void HandleLinks(string processName, int seconds, DateTime time) { - try + Task.Run(() => { - List links = config.Links != null ? config.Links : new List(); - foreach (LinkModel link in links) + try { - if (link.ProcessList != null - && link.ProcessList.Count >= 2 - && link.ProcessList.Contains(processName)) + List links = config.Links != null ? config.Links : new List(); + foreach (LinkModel link in links) { - // 属于关联进程 - foreach (string linkProcess in link.ProcessList) + if (link.ProcessList != null + && link.ProcessList.Count >= 2 + && link.ProcessList.Contains(processName)) { - if (linkProcess != processName) + // 属于关联进程 + foreach (string linkProcess in link.ProcessList) { - if (IsProcessRuning(linkProcess)) + if (linkProcess != processName) { - // 同步更新 - data.Set(linkProcess, seconds, time); - } + if (IsProcessRuning(linkProcess)) + { + // 同步更新 + data.SaveAppDuration(linkProcess, seconds, time); + } + } } + break; } - break; } - } - } - catch (Exception ex) - { - Logger.Error(ex.Message + ",关联进程更新错误,Process Name: " + processName + ",Time: " + seconds); - } + } + catch (Exception ex) + { + Logger.Error(ex.Message + ",关联进程更新错误,Process Name: " + processName + ",Time: " + seconds); + } + }); } #region 判断进程是否在运行中 @@ -410,10 +427,10 @@ namespace Core.Servicers.Instances if (!string.IsNullOrEmpty(app)) { - var time = activeStartTime; + var time = new DateTime(activeStartTime.Ticks); // 更新计时 - TimeSpan timeSpan = DateTime.Now - activeStartTime; + TimeSpan timeSpan = DateTime.Now - time; int seconds = (int)timeSpan.TotalSeconds; @@ -425,15 +442,12 @@ namespace Core.Servicers.Instances if (seconds > 0) { - Task.Run(() => - { - data.Set(app, seconds, time); + data.SaveAppDuration(app, seconds, time); - // 关联进程更新 - HandleLinks(app, seconds, time); + // 关联进程更新 + HandleLinks(app, seconds, time); - Logger.Info("status:" + sleepStatus + ",process:" + app + ",seconds:" + seconds + ",start:" + activeStartTime.ToString() + ",end:" + DateTime.Now.ToString() + ",time:" + time.ToString()); - }); + //Logger.Info("status:" + sleepStatus + ",process:" + app + ",seconds:" + seconds + ",start:" + activeStartTime.ToString() + ",end:" + DateTime.Now.ToString() + ",time:" + time.ToString()); } activeStartTime = DateTime.Now; @@ -447,6 +461,11 @@ namespace Core.Servicers.Instances /// private void HandleWebServiceConfig() { + if (config == null) + { + return; + } + if (config.General.IsWebEnabled) { browserObserver.Start(); diff --git a/Core/Servicers/Interfaces/IData.cs b/Core/Servicers/Interfaces/IData.cs index 1378c3f9668abc88c92f9941f37e10933279a3c0..11c02ac130cea24fc3d746444581ed65393dfd4e 100644 --- a/Core/Servicers/Interfaces/IData.cs +++ b/Core/Servicers/Interfaces/IData.cs @@ -12,11 +12,12 @@ namespace Core.Servicers.Interfaces { /// - /// 设置进程数据 + /// 保存APP使用时长数据 /// - /// 进程名称 - /// 时长(秒) - void Set(string processName, int seconds, DateTime? time = null); + /// 进程名称 + /// 时长(秒) + /// 记录开始时间 + void SaveAppDuration(string processName_, int duration_, DateTime startDateTime_); /// /// 获取今天的数据