Ejemplo n.º 1
0
        private static bool LoadConfig()
        {
            var file = Domain.ConfigFile;

            if (!File.Exists(file))
            {
                AppSettings.CreateNewConfig();
            }
            else
            {
                try
                {
                    var content = ConcurrentFile.ReadAllText(file);
                    AppSettings.Load(JsonConvert.DeserializeObject <AppSettings>(content));
                }
                catch (JsonException e)
                {
                    var result = MessageBox.Show(@"载入配置文件时失败,用默认配置覆盖继续打开吗?\r\n" + e.Message,
                                                 "Osu Player", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result == MessageBoxResult.Yes)
                    {
                        AppSettings.CreateNewConfig();
                    }
                    else
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 2
0
        protected virtual T LoadSettings <T>(string fileName = null, bool writeLog = false)
        {
            try
            {
                Type clsT = typeof(T);

                string saveName = Path.Combine(SettingsPath, (fileName ?? clsT.Name) + ".json");

                if (!Directory.Exists(SettingsPath))
                {
                    Directory.CreateDirectory(SettingsPath);
                }

                string json = ConcurrentFile.ReadAllText(saveName);
                if (writeLog)
                {
                    var fileInfo = new FileInfo(saveName);
                    Logger.Success($"Loaded settings from \"{Path.Combine("~", fileInfo.Directory?.Name, fileInfo.Name)}\".");
                }

                return(Newtonsoft.Json.JsonConvert.DeserializeObject <T>(json));
            }
            catch (FileNotFoundException)
            {
                return(default);
Ejemplo n.º 3
0
Archivo: Food.cs Proyecto: Gtsz/Daylily
        public override CommonMessageResponse Message_Received(CommonMessage messageObj)
        {
            _cm = messageObj;
            string[] fullContent = ConcurrentFile.ReadAllLines(_content);

            if (EnabledAlbumId > 0 || DisabledAlbumId > 0)
            {
                return(_cm.PermissionLevel == PermissionLevel.Root
                    ? ModuleManageAlbum(fullContent)
                    : new CommonMessageResponse(LoliReply.RootOnly, _cm));
            }

            if (Like > 0)
            {
                return(ModuleLike(fullContent));
            }

            if (Hot)
            {
                return(ModuleHot());
            }

            if (Top || TopNum > 0)
            {
                return(ModuleTop());
            }

            if (ClearCache)
            {
                ClearContent();
                return(new CommonMessageResponse("已重新建立缓存", _cm));
            }

            return(ModuleSearch(fullContent));
        }
Ejemplo n.º 4
0
        private static string GetRandomPhoto(string dir)
        {
            string[] innerContent = ConcurrentFile.ReadAllLines(Path.Combine(dir, ".content"));
            string   innerChoice  = innerContent[StaticRandom.Next(0, innerContent.Length)];
            string   file         = Path.Combine(dir, innerChoice);

            return(file);
        }
Ejemplo n.º 5
0
 private static void OnCurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
     if (!e.IsTerminating)
     {
         return;
     }
     MessageBox.Show(string.Format("发生严重错误,即将退出。。。详情请查看error.log。{0}{1}", Environment.NewLine, (e.ExceptionObject as Exception)?.Message), "Osu Player", MessageBoxButton.OK, MessageBoxImage.Error);
     ConcurrentFile.AppendAllText("error.log", string.Format(@"===================={0}===================={1}{2}{3}{4}", DateTime.Now, Environment.NewLine, e.ExceptionObject, Environment.NewLine, Environment.NewLine));
     Environment.Exit(1);
 }
Ejemplo n.º 6
0
        private static void WriteToLog(string contents)
        {
            contents = string.Format("-----{0} {1}{2}{3}{4}", DateTime.Now.ToLongDateString(),
                                     DateTime.Now.ToLongTimeString(), Environment.NewLine, contents, Environment.NewLine + Environment.NewLine);
            string logPath = Path.Combine(Domain.CurrentDirectory, "log");

            if (!Directory.Exists(logPath))
            {
                Directory.CreateDirectory(logPath);
            }
            ConcurrentFile.AppendAllText(Path.Combine(logPath, "exception.log"), contents);
        }
Ejemplo n.º 7
0
        protected void SaveSettings <T>(T cls, string fileName = null)
        {
            Type clsT = cls.GetType();

            string saveName = Path.Combine(SettingsPath, (fileName ?? clsT.Name) + ".json");

            if (!Directory.Exists(SettingsPath))
            {
                Directory.CreateDirectory(SettingsPath);
            }

            ConcurrentFile.WriteAllText(saveName, Newtonsoft.Json.JsonConvert.SerializeObject(cls));
        }
Ejemplo n.º 8
0
        private static void LoadExtend()
        {
            if (!Directory.Exists(ExtendedDir))
            {
                Directory.CreateDirectory(ExtendedDir);
            }

            foreach (var dir in Directory.GetDirectories(ExtendedDir))
            {
                string metaFile = Path.Combine(dir, "metadata.json");
                if (!File.Exists(metaFile))
                {
                    Logger.Error(dir + "内未包含metadata.json");
                    continue;
                }
                Logger.Info("已发现 " + new DirectoryInfo(dir).Name);

                string     json       = ConcurrentFile.ReadAllText(metaFile);
                ExtendMeta extendMeta = JsonConvert.DeserializeObject <ExtendMeta>(json);

                ExtendPlugin extendPlugin = new ExtendPlugin()
                {
                    Program  = extendMeta.Program,
                    File     = new FileInfo(Path.Combine(dir, extendMeta.File)).FullName,
                    Name     = extendMeta.Name,
                    Author   = extendMeta.Author,
                    Major    = extendMeta.Major,
                    Minor    = extendMeta.Minor,
                    Patch    = extendMeta.Patch,
                    State    = extendMeta.State,
                    Helps    = extendMeta.Help,
                    Commands = extendMeta.Command,
                };

                if (extendPlugin.Commands.Length != 0)
                {
                    foreach (var item in extendPlugin.Commands)
                    {
                        CommandMap.TryAdd(item, extendPlugin.GetType());
                        CommandMapStatic.TryAdd(item, extendPlugin);
                    }
                    Logger.Origin($"命令 \"{extendMeta.Name}\" ({string.Join(',', extendPlugin.Commands)}) 已经加载完毕。");
                }
                else
                {
                    Logger.Warn($"\"{extendMeta.Name}\"尚未设置命令,因此无法被用户激活。");
                    Logger.Origin($"命令 \"{extendMeta.Name}\" 已经加载完毕。");
                }
            }
        }
Ejemplo n.º 9
0
        protected void SaveSettings <T>(T cls, string fileName = null, bool writeLog = false)
        {
            Type clsT = cls.GetType();

            string saveName = Path.Combine(SettingsPath, (fileName ?? clsT.Name) + ".json");

            if (!Directory.Exists(SettingsPath))
            {
                Directory.CreateDirectory(SettingsPath);
            }

            ConcurrentFile.WriteAllText(saveName, Newtonsoft.Json.JsonConvert.SerializeObject(cls));
            if (writeLog)
            {
                var fileInfo = new FileInfo(saveName);
                Logger.Success($"写入了 {Path.Combine("~", fileInfo.Directory?.Name, fileInfo.Name)}。");
            }
        }
Ejemplo n.º 10
0
        protected T LoadSettings <T>(string fileName = null)
        {
            try
            {
                Type clsT = typeof(T);

                string saveName = Path.Combine(SettingsPath, (fileName ?? clsT.Name) + ".json");

                if (!Directory.Exists(SettingsPath))
                {
                    Directory.CreateDirectory(SettingsPath);
                }

                string json = ConcurrentFile.ReadAllText(saveName);
                return(Newtonsoft.Json.JsonConvert.DeserializeObject <T>(json));
            }
            catch (FileNotFoundException)
            {
                return(default);
Ejemplo n.º 11
0
        public override CoolQRouteMessage OnMessageReceived(CoolQScopeEventArgs scope)
        {
            var routeMsg = scope.RouteMessage;

            _cm = routeMsg;
            string[] fullContent = ConcurrentFile.ReadAllLines(_content);

            if (EnabledAlbumId > 0 || DisabledAlbumId > 0)
            {
                return(_cm.CurrentAuthority == Authority.Root
                    ? ModuleManageAlbum(fullContent)
                    : routeMsg.ToSource(DefaultReply.RootOnly));
            }

            if (Like > 0)
            {
                return(ModuleLike(fullContent));
            }

            if (Hot)
            {
                return(ModuleHot());
            }

            if (Top || TopNum > 0)
            {
                return(ModuleTop());
            }

            if (ClearCache)
            {
                ClearContent();
                return(_cm
                       .ToSource("已重新建立缓存")
                       .ForceToSend());
            }

            return(ModuleSearch(fullContent));
        }
Ejemplo n.º 12
0
        public static void LoadSecret()
        {
            var    file = new FileInfo(Path.Combine(Domain.SecretPath, "secret.json"));
            string json;
            Secret secret;

            if (!file.Exists)
            {
                secret = new Secret();
                json   = Newtonsoft.Json.JsonConvert.SerializeObject(secret);
                ConcurrentFile.WriteAllText(file.FullName, json.ToJsonFormat());

                Logger.Error("请完善secret配置。");
                Console.ReadKey();
                Environment.Exit(0);
            }

            json   = ConcurrentFile.ReadAllText(file.FullName);
            secret = Newtonsoft.Json.JsonConvert.DeserializeObject <Secret>(json);

            // 读设置
            DbHelper.ConnectionString.Add("cabbage", secret.ConnectionStrings.DefaultConnection);
            DbHelper.ConnectionString.Add("daylily", secret.ConnectionStrings.MyConnection);

            OsuApiConfig.ApiKey   = secret.OsuSettings.ApiKey;
            OsuApiConfig.UserName = secret.OsuSettings.UserName;
            OsuApiConfig.Password = secret.OsuSettings.Password;

            Signature.AppId      = secret.CosSettings.AppId;
            Signature.SecretId   = secret.CosSettings.SecretId;
            Signature.SecretKey  = secret.CosSettings.SecretKey;
            Signature.BucketName = secret.CosSettings.BucketName;

            CoolQHttpApiClient.ApiUrl       = secret.BotSettings.PostUrl;
            CoolQCode.CqPath                = secret.BotSettings.CqDir;
            DaylilyCore.Current.CommandFlag = secret.BotSettings.CommandFlag;

            TuLingSecret.ApiKeys = secret.TuLingSettings.ApiKey;
        }
Ejemplo n.º 13
0
        private static bool LoadConfig()
        {
            var file = Domain.ConfigFile;

            if (!File.Exists(file))
            {
                AppSettings.CreateNewConfig();
            }
            else
            {
                try
                {
                    var content = ConcurrentFile.ReadAllText(file);
                    AppSettings.Load(JsonConvert.DeserializeObject <AppSettings>(content,
                                                                                 new JsonSerializerSettings
                    {
                        TypeNameHandling = TypeNameHandling.Auto
                    }
                                                                                 )
                                     );
                }
                catch (JsonException ex)
                {
                    var result = MessageBox.Show("载入配置文件时失败,用默认配置覆盖继续打开吗?" + Environment.NewLine + ex.Message,
                                                 "Osu Player", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result == MessageBoxResult.Yes)
                    {
                        AppSettings.CreateNewConfig();
                    }
                    else
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 14
0
Archivo: Help.cs Proyecto: Gtsz/Daylily
        public override CommonMessageResponse Message_Received(CommonMessage messageObj)
        {
            _cm = messageObj;
            if (UseList)
            {
                return(new CommonMessageResponse(ShowList(), _cm));
            }
            if (CommandName == null)
            {
                using (Session session = new Session(20000, _cm.Identity, _cm.UserId))
                {
                    Dictionary <string, string> dic = new Dictionary <string, string>
                    {
                        { "你是谁", "你是谁。" },
                        { "基础帮助", "查看通用的基础使用方法。(/help -list)" },
                        { "查列表", "查看所有可用的命令和应用列表。" }
                    };

                    string[] sb = dic.Select(k => $"【{k.Key}】 {k.Value}").ToArray();

                    string msg = "被召唤啦!请选择你要查看的帮助类型:\r\n" + string.Join("\r\n", sb);
                    SendMessage(new CommonMessageResponse(msg, _cm));
                    try
                    {
                        var a = dic.Select(k => k.Key).ToArray();

                        CommonMessage cm;
                        do
                        {
                            cm = session.GetMessage();
                            if (cm.Message.Contains("你是谁"))
                            {
                                return(new CommonMessageResponse(
                                           new FileImage(Path.Combine(StaticDir, "help.jpg")).ToString(), _cm));
                            }
                            if (cm.Message.Contains("基础帮助"))
                            {
                                if (cm.MessageType == MessageType.Private)
                                {
                                    return(new CommonMessageResponse(
                                               ConcurrentFile.ReadAllText(Path.Combine(StaticDir, "common.txt")), _cm));
                                }
                                SendMessage(new CommonMessageResponse("已发送至私聊,请查看。", _cm, true));
                                SendMessage(new CommonMessageResponse(
                                                ConcurrentFile.ReadAllText(Path.Combine(StaticDir, "common.txt")),
                                                new Identity(_cm.UserId, MessageType.Private)));
                                return(null);
                            }

                            if (cm.Message.Contains("查列表"))
                            {
                                return(new CommonMessageResponse(ShowList(), _cm));
                            }
                            SendMessage(new CommonMessageResponse("请回复大括号内的文字。", _cm));
                        } while (!a.Contains(cm.Message));

                        return(new CommonMessageResponse(ShowList(), _cm));
                    }
                    catch (TimeoutException)
                    {
                        return(new CommonMessageResponse("没人鸟我,走了.jpg", _cm));
                    }
                }
            }
            else
            {
                return(new CommonMessageResponse(ShowDetail().Trim('\n').Trim('\r'), _cm));
            }
        }
Ejemplo n.º 15
0
 private static void SaveCache()
 {
     ConcurrentFile.WriteAllText(CachePath, Newtonsoft.Json.JsonConvert.SerializeObject(UserDictionary, Newtonsoft.Json.Formatting.Indented));
 }
Ejemplo n.º 16
0
 private static void Backup()
 {
     ConcurrentFile.WriteAllText("player.db.bak", JsonConvert.SerializeObject(_dbJsonObject));
 }
Ejemplo n.º 17
0
        public override CoolQRouteMessage OnMessageReceived(CoolQScopeEventArgs scope)
        {
            var routeMsg = scope.RouteMessage;

            _routeMsg = routeMsg;
            if (UseList)
            {
                return(routeMsg
                       .ToSource(ShowList())
                       .ForceToSend());
            }
            if (CommandName == null)
            {
                using (Session session = new Session(20000, _routeMsg.Identity, _routeMsg.UserId))
                {
                    Dictionary <string, string> dic = new Dictionary <string, string>
                    {
                        { "你是谁", "你是谁。" },
                        { "基础帮助", "查看通用的基础使用方法。" },
                        { "查列表", "查看所有可用的命令和应用列表。(/help -list)" }
                    };

                    string[] sb = dic.Select(k => $"【{k.Key}】 {k.Value}").ToArray();

                    string msg = "被召唤啦!请选择你要查看的帮助类型:\r\n" + string.Join("\r\n", sb);
                    SendMessage(routeMsg
                                .ToSource(msg)
                                .ForceToSend()
                                );
                    try
                    {
                        var keys = dic.Select(k => k.Key).ToArray();

                        CoolQRouteMessage cm;
                        do
                        {
                            cm = (CoolQRouteMessage)session.GetMessage();
                            if (cm.RawMessage.Contains("你是谁"))
                            {
                                return(routeMsg
                                       .ToSource(new FileImage(Path.Combine(StaticDir, "help.jpg")).ToString())
                                       .ForceToSend());
                            }
                            if (cm.Message.RawMessage.Contains("基础帮助"))
                            {
                                if (cm.MessageType == MessageType.Private)
                                {
                                    return(routeMsg
                                           .ToSource(ConcurrentFile.ReadAllText(Path.Combine(StaticDir, "common.txt")))
                                           .ForceToSend());
                                }

                                SendMessage(routeMsg
                                            .ToSource("已发送至私聊,请查看。", true)
                                            .ForceToSend()
                                            );
                                var helpStr = ConcurrentFile.ReadAllText(Path.Combine(StaticDir, "common.txt"));
                                SendMessage(new CoolQRouteMessage(helpStr, new CoolQIdentity(_routeMsg.UserId, MessageType.Private))
                                            .ForceToSend()
                                            );
                                return(null);
                            }

                            if (cm.RawMessage.Contains("查列表"))
                            {
                                return(routeMsg
                                       .ToSource(ShowList())
                                       .ForceToSend());
                            }

                            SendMessage(routeMsg.ToSource("请回复大括号内的文字。"));
                        } while (!keys.Contains(cm.RawMessage));

                        return(routeMsg
                               .ToSource(ShowList())
                               .ForceToSend());
                    }
                    catch (TimeoutException)
                    {
                        return(routeMsg
                               .ToSource("没人鸟我,走了.jpg")
                               .ForceToSend());
                    }
                }
            }

            return(routeMsg
                   .ToSource(ShowDetail())
                   .ForceToSend());
        }
Ejemplo n.º 18
0
        public ImageInfo(string source)
        {
            // TODO 这里还没考虑 file=base64:// 的情况
            const string file     = "file=";
            var          index    = source.IndexOf(file, StringComparison.Ordinal) + file.Length;
            var          index2   = source.IndexOf(",", index, StringComparison.Ordinal);
            string       fileName = source.Substring(index, index2 - index) + ".cqimg";
            string       fullPath = Path.Combine(CqCode.CqRoot, "data", "image", fileName);

            FileInfo = new FileInfo(fullPath);

            string[] settings;
            if (!FileInfo.Exists)
            {
                string tmp = AssistApi.GetImgFile(fileName);
                settings = tmp.Replace("\r", "").Trim('\n').Split('\n');
            }
            else
            {
                settings = ConcurrentFile.ReadAllLines(fullPath);
            }

            foreach (var line in settings)
            {
                string[] result = line.Split('=');
                if (result.Length < 2)
                {
                    continue;
                }

                var key   = result[0];
                var value = "";
                for (int i = 1; i < result.Length; i++)
                {
                    value += result[i] + "=";
                }
                value = value.Remove(value.Length - 1);
                switch (key)
                {
                case "md5":
                    Md5 = value;
                    break;

                case "width":
                    Width = int.Parse(value);
                    break;

                case "height":
                    Height = int.Parse(value);
                    break;

                case "size":
                    Size = long.Parse(value);
                    break;

                case "url":
                    Url = value;
                    break;

                case "addtime":
                    Addtime = new DateTime(1970, 1, 1).ToLocalTime().AddSeconds(int.Parse(value));
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
        }
Ejemplo n.º 19
0
 public static void SaveDefault()
 {
     ConcurrentFile.WriteAllText(Domain.ConfigFile, JsonConvert.SerializeObject(Default, Formatting.Indented));
 }