Пример #1
0
        private static void CheckForManualInstalledMods()
        {
            ModFile[] mods      = JsonCommon.GetAllMods();
            ModFile[] instmods  = InstalledMods.GetInstalledMods();
            string    addedmods = "";

            for (int i = 0; i < mods.Length; i++)
            {
                if (!string.IsNullOrEmpty(mods[i].DelInfo))
                {
                    if (File.Exists(Path.Combine(Utilities.GameDirectory, mods[i].DelInfo)))
                    {
                        bool IsInstalled = false;
                        for (int x = 0; x < instmods.Length; x++)
                        {
                            if (mods[i].ModId == instmods[x].ModId)
                            {
                                IsInstalled = true;
                                break;
                            }
                        }
                        if (!IsInstalled)
                        {
                            addedmods += mods[i].ModId + ", ";
                            InstalledMods.AddInstalledMod(mods[i].ModId);
                        }
                    }
                }
            }
            if (!String.IsNullOrEmpty(addedmods))
            {
                var conf = MessageBox.Show($"Some manually installed mods have been detected, adding it to database. Detected mods: {addedmods.Split(',').Length} \n" + addedmods, "Installed mods detected!", MessageBoxButtons.OK);
            }
        }
Пример #2
0
        internal static void setSceneJson(string json)
        {
            // Calling Newtonsoft.Json.Linq.JObject.Parse here results in a memory leak.
            var o = Newtonsoft.Json.Linq.JObject.Parse(json);

            Scene.scene_internal = JsonCommon.convertScene(o);
        }
Пример #3
0
        private static JObject UserInfo(string token, string uid, ref string errMsg)
        {
            try
            {
                string result;

                using (var wc = new HttpClient())
                {
                    var url = UserInfoUrl + string.Format(UserInfoUrlParams, uid, token);

                    var response = wc.GetAsync(url).Result;

                    result = response.Content.ReadAsStringAsync().Result;
                }

                var user = JsonCommon.Deserialize(result);

                return(user);
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;

                return(null);
            }
        }
Пример #4
0
        public StreamingService(BotService bot, RocksmithService rocksmith)
        {
            // Бот
            Bot       = bot;
            Rocksmith = rocksmith;

            // Настройки приложения
            JObject settings = JsonCommon.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "settings.json"));

            contentProviders = new List <ContentProvider>();
            Broadcast        = new Broadcast();

            JToken streamingConfigs = settings["streaming"];

            if (!streamingConfigs.IsNullOrEmpty())
            {
                if (!streamingConfigs["twitch"].IsNullOrEmpty())
                {
                    Twitch = new TwitchConnector(Bot, JsonConvert.DeserializeObject <TwitchConnectorConfig>(streamingConfigs["twitch"].ToString()));
                }
                if (!streamingConfigs["youtube"].IsNullOrEmpty())
                {
                    Youtube = new YoutubeConnector(Bot, JsonConvert.DeserializeObject <YoutubeConnectorConfig>(streamingConfigs["youtube"].ToString()));
                }
            }

            InitProviders((JObject)settings["providers"]);
            InitWidgetsSchemes(settings["scheme"].ToString());
            InitBroadcastHandlers();
        }
Пример #5
0
        private JObject GetAccessToken(string code, ref string errorMsg)
        {
            var data = new SortedDictionary <string, string>
            {
                { "client_id", Credential.ClientId },
                { "client_secret", Credential.ClientSecret },
                { "code", code }
            };

            using var client = GetHttpClientProxy();
            try
            {
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                var response = client.PostAsync(_oauthUrl, new FormUrlEncodedContent(data)).Result;
                var result   = response.Content.ReadAsStringAsync().Result;
                if (result.Contains("bad_verification_code"))
                {
                    errorMsg = "bad_verification_code";
                    return(null);
                }
                return(JsonCommon.Deserialize(result));
            }

            catch (Exception ex)
            {
                errorMsg = ex.Message;

                return(null);
            }
        }
Пример #6
0
        private JObject UserInfo(string token, ref string errMsg)
        {
            try
            {
                string result;

                using (var wc = new HttpClient())
                {
                    var content = _userInfoUrlParams + token;

                    var response = wc.PostAsync(_userInfoUrl, new StringContent(content)).Result;

                    result = response.Content.ReadAsStringAsync().Result;
                }

                var user = JsonCommon.Deserialize(result);

                return(user);
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;

                return(null);
            }
        }
Пример #7
0
        private JObject GetAccessToken(string code, ref string errMsg)
        {
            var data = new SortedDictionary <string, string>
            {
                { "client_id", Credential.ClientId },
                { "client_secret", Credential.ClientSecret },
                { "code", code },
                { "redirect_uri", RedirectUri }
            };

            var Params = string.Join("&", data.Select(x => x.Key + "=" + x.Value).ToArray());

            using var client = new HttpClient();
            try
            {
                var response = client.PostAsync(_oauthUrl, new StringContent(Params)).Result;

                var result = response.Content.ReadAsStringAsync().Result;

                return(JsonCommon.Deserialize(result));
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;

                return(null);
            }
        }
Пример #8
0
        public RocksmithService()
        {
            rocksmithDir = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "rocksmith"));

            Config = JsonCommon.Load <RocksmithConfig>(Path.Combine(rocksmithDir.FullName, "rocksmith.json"));
            Queue  = new RocksmithQueue(rocksmithDir.FullName, Config.UserLimit);
        }
Пример #9
0
        private static bool HandleHeaders(ExcelConvertorSettings settings, IDataRecord reader, ref string[] headers,
                                          ref int[] mandatoryColumnsIndexes)
        {
            if (reader.FieldCount == 0 || reader.RowHasEmptyCells())
            {
                return(false);
            }

            var currentRow = reader.GetCurrentRow().Select(s => JsonCommon.StringCleanup(s.ToString()));

            var tmpHeader = JsonCommon.ToCamelCase(currentRow).ToArray();

            var mci = new List <int>();

            for (var i = 0; i < tmpHeader.Count(); i++)
            {
                if (settings.MandatoryColumns.Any(s => tmpHeader[i]
                                                  .Equals(s, StringComparison.InvariantCultureIgnoreCase)))
                {
                    mci.Add(i);
                }
            }

            mandatoryColumnsIndexes = mci.ToArray();

            headers = tmpHeader;
            return(true);
        }
Пример #10
0
 public Node CreateNode(string name, Node node)
 {
     if (nodes.ContainsKey(name))
     {
         throw new ArgumentException("Node with name " + name + " already exists");
     }
     Mana.Internal.SceneInterface.createNode(name, JsonCommon.convertNode(node).ToString());
     return(nodes[name]);
 }
        private static Task HandleExceptionAsync(HttpContext context, int statusCode, string msg)
        {
            var data = new ApiErrResult(statusCode, msg);

            var result = new JsonCommon().Serializer(data);

            context.Response.ContentType = "application/json;charset=utf-8";

            return(context.Response.WriteAsync(result));
        }
Пример #12
0
        private void LoadGUI(object sender, EventArgs e)
        {
            InitTimer();                                //progress timer

            AllocConsole();                             //enables console
            JsonCommon.OverrideModInstallerVariables(); //overrides vars if possible

            //check if in vs
            string dir = Directory.GetCurrentDirectory();

            for (int i = 0; i < 3; i++)
            {
                dir = Directory.GetParent(dir).ToString(); //move up 3 dirs
            }
            dir += @"\bin\";                               //add bin
            Console.WriteLine(ModInstallerCommon.Files.MainFiledir);
            Console.WriteLine("Detecting for" + ModInstallerCommon.Files.execdir);
            if (!File.Exists(ModInstallerCommon.Files.execdir) && !ModInstallerCommon.BypassExec && !Directory.Exists(dir))
            {
                MessageBox.Show("ModInstaller cannot find the executable! Make sure my location is in a folder inside the h3vr directory! Just in case, I'll pull up a tutorial for you.", "Exectuable not found!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                var psi = new ProcessStartInfo
                {
                    FileName        = "https://youtu.be/LBcxS_mYLFE?t=21",
                    UseShellExecute = true
                };
                Process.Start(psi);
                Application.Exit();
            }

            var onlineversion = new Version(JsonModList.GetDeserializedModListFormatOnline(JsonCommon.DatabaseInfo).Modlist[0].Version);

            if (ModInstallerCommon.ModInstallerVersion.CompareTo(onlineversion) < 0)
            {
                MessageBox.Show("H3VRModInstaller is out of date! (" + ModInstallerCommon.ModInstallerVersion + " vs " + onlineversion + ")", "Wrong version detected!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                var psi = new ProcessStartInfo
                {
                    FileName        = JsonModList.GetDeserializedModListFormatOnline(JsonCommon.DatabaseInfo).Modlist[0].Website,
                    UseShellExecute = true
                };
                Process.Start(psi);
            }

            InstallButton.Hide();
            UpdateButton.Hide();
            ModVer.Hide();
            Delete.Hide();
            CheckButton.Hide();
            InstalledModsList.Hide();

            ModsEnabled.Checked = true;
            UpdateModList();
            UpdateCatagories();
        }
Пример #13
0
        public void Init(string fileName)
        {
            JObject data = JsonCommon.Load(fileName);

            Config     = fileName;
            ConfigData = data;

            ProcessID  = -1;
            ProgramID  = ConfigData["id"].ToString();
            Module     = ConfigData["module"].ToString();
            LastStatus = GetLastStatus();
            Version    = new Version(ConfigData["version"]?.ToString() ?? "0.0.0");
        }
Пример #14
0
        private void InitWidgetsSchemes(string current)
        {
            WidgetsSchemes = new List <WidgetsScheme>();

            string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "widgets");

            string[] files = Directory.GetFiles(fileName, "*.json");
            foreach (string file in files)
            {
                WidgetsSchemes.Add(JsonCommon.Load <WidgetsScheme>(file));
            }

            WidgetsScheme = WidgetsSchemes.FirstOrDefault(s => s.Name == current);
        }
Пример #15
0
        private ETLUpdateRecord AddUpdateRecord(string file)
        {
            string extension = Path.GetExtension(file).Replace(".", string.Empty);
            string fileName  = Path.GetFileName(file);
            // На программу подразумевается одна конфигурация и один модуль
            ETLProcess prc = pumps.FirstOrDefault(p => extension.IsMatch("json")
                ? p.Config == fileName
                : p.Module == fileName);

            // В реестре закачка отсутствует, есть только программный модуль
            if (prc == null && extension.IsMatch("dll"))
            {
                return(null);
            }

            ETLUpdateRecord rec = null;

            switch (extension)
            {
            case "json":
                JObject data      = JsonCommon.Load(file);
                string  programID = prc == null ? data["id"].ToString() : prc.ProgramID;

                rec = new ETLUpdateRecord {
                    Config    = fileName,
                    Module    = data["module"].ToString(),
                    ProgramID = programID
                };

                Updates[programID] = rec;
                break;

            case "dll":
                // Если записи нет, то добавляем, иначе нужный модуль уже должен быть прописан в обновление
                if (!Updates.ContainsKey(prc.ProgramID))
                {
                    rec = new ETLUpdateRecord {
                        ProgramID = prc.ProgramID,
                        Module    = fileName
                    };

                    Updates.Add(prc.ProgramID, rec);
                }
                break;
            }

            return(rec);
        }
Пример #16
0
        /// <summary>
        /// args[0] - id закачки;
        /// args[1] - тип конфигурации: -h - история, -s - строка -f - файл
        /// args[2] - конфигурация: в зависимости от args[1] это строка конфигурации или имя файла
        /// </summary>
        static void Main(string[] args)
        {
            try
            {
                context = new ETLContext(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config", "ETLSettings.json"));
                context.Initialize();
                context.DB.Connect();

                decimal sessNo = Convert.ToDecimal(args[0]);
                historyRecord = context.History[sessNo];

                JObject config = null;
                switch (args[1])
                {
                case "-f":
                    config = JsonCommon.Load(Path.Combine(context.Settings.Registry.ProgramsPath, args[2]));
                    break;

                case "-h":
                    config = (JObject)JsonConvert.DeserializeObject(historyRecord.config);
                    break;

                case "-s":
                    config = (JObject)JsonConvert.DeserializeObject(args[2]);
                    break;
                }

                if (config == null)
                {
                    return;
                }

                // Инициализация
                Init(sessNo, config["id"].ToString(), config["module"].ToString());

                // Выполнение
                Exec(sessNo, config);
            }
            catch (Exception ex)
            {
                Logger.WriteToTrace($"Критическая ошибка загрузки закачки: {ex}", TraceMessageKind.CriticalError);
            }
            finally
            {
                program?.Dispose();
                Logger.CloseLogFile();
            }
        }
Пример #17
0
        private void Init()
        {
            // Загрузка текстовых команд
            commandList = new List <string>();

            JObject settings = JsonCommon.Load(Path.Combine(botDir.FullName, "bot.json"));

            if (!settings.IsNullOrEmpty())
            {
                LogMessages  = Convert.ToBoolean(settings["logMessages"]);
                commandList  = JsonConvert.DeserializeObject <List <string> >(settings["commands"].ToString());
                SoundTimeout = Convert.ToInt32(settings["soundTimeout"].ToString());
            }

            // Загрузка звуковых команд
            soundCommandList = JsonCommon.Load <Dictionary <string, string> >(Path.Combine(botDir.FullName, "sound.json"));
        }
Пример #18
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string method = context.Request.Params["method"];

            if ("list".Equals(method))
            {
                string       ajax = context.Request.Params["ajax"];
                BrandIdeaDAO dao  = new BrandIdeaDAO();
                BrandIdea    bi   = new BrandIdea();
                bi.biType = context.Request.Params["biType"];
                DataSet ds     = dao.select(bi);
                string  result = "";
                if (String.IsNullOrEmpty(ajax))
                {
                    result = "_list = " + JsonCommon.ds2json(ds);
                }
                else
                {
                    result = JsonCommon.ds2json(ds);
                }
                context.Response.Write(result);
            }
            else if ("detail".Equals(method))
            {
                BrandIdeaDAO dao = new BrandIdeaDAO();
                BrandIdea    bi  = new BrandIdea();
                bi.biId = context.Request.Params["biId"];
                DataSet ds   = dao.select(bi);
                string  json = JsonCommon.ds2json(ds);
                context.Response.Write(json);
            }
            else if ("save".Equals(method))
            {
                string       biContent = HttpUtility.UrlDecode((context.Request.Params["biContent"]).Replace("@", "%"));
                string       biType    = context.Request.Params["biType"];
                string       biId      = context.Request.Params["biId"];
                BrandIdeaDAO dao       = new BrandIdeaDAO();
                BrandIdea    bi        = new BrandIdea();
                bi.biId      = biId;
                bi.biContent = biContent;
                bi.biType    = biType;
                dao.update(bi);
            }
        }
Пример #19
0
 public AuthenticateDemoService()
 {
     _jsonCommon           = new JsonCommon();
     _restClient           = new RestClient("http://ai.baidu.com");
     _restClient.UserAgent =
         "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36";
     _request =
         new RestRequest(
             $"aidemo",
             Method.POST)
     {
         RequestFormat = RestSharp.DataFormat.Json
     };
     _request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
     _request.AddHeader("Origin", "http://ai.baidu.com");
     _request.AddHeader("Host", "ai.baidu.com");
     _request.AddHeader("Referer", "http://ai.baidu.com/tech/imagecensoring");
     _request.AddHeader("Accept", "*/*");
     _request.AddHeader("Accept-Language", "zh-CN,zh;q=0.9");
     _request.AddParameter("type", "user_defined");
 }
Пример #20
0
        private static JObject UserInfo(object accessToken, ref string errorMsg)
        {
            try
            {
                string result;
                _userInfoUrl = string.Format(_userInfoUrl, accessToken);
                using (var wc = new HttpClient())
                {
                    wc.DefaultRequestHeaders.Add("User-Agent", @"Mozilla/5.0 (Windows NT 10; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0");
                    var response = wc.GetAsync(_userInfoUrl).Result;
                    result = response.Content.ReadAsStringAsync().Result;
                }
                var user = JsonCommon.Deserialize(result);
                return(user);
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;

                return(null);
            }
        }
Пример #21
0
        private void LoadGUI(object sender, EventArgs e)
        {
            KeyDown += Form_KeyDown;

            if (!File.Exists(Utilities.ModCache))
            {
                MessageBox.Show("Thank you for downloading H3VRModInstaller!\nIf there are any issues, or if you want a mod added, please hit us up on the Homebrew discord (@Frityet and @Potatoes)", "Thank you!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            InitTimer();                                //progress timer
            //AllocConsole(); //enables console
            JsonCommon.OverrideModInstallerVariables(); //overrides vars if possible

            var onlineversion = new Version(JsonModList.GetDeserializedModListFormatOnline(JsonCommon.DatabaseInfo)
                                            .Modlist[0].Version);

            if (ModInstallerCommon.ModInstallerVersion.CompareTo(onlineversion) < 0)
            {
                MessageBox.Show("H3VRModInstaller is out of date! (" + ModInstallerCommon.ModInstallerVersion + " vs " + onlineversion + ")", "Out of date version detected!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                var psi = new ProcessStartInfo
                {
                    FileName = JsonModList.GetDeserializedModListFormatOnline(JsonCommon.DatabaseInfo)
                               .Modlist[0]
                               .Website,
                    UseShellExecute = true
                };
                Process.Start(psi);
            }

            InstallButton.Hide();
            UpdateButton.Hide();
            ModVer.Hide();
            Delete.Hide();
            CheckButton.Hide();
            UpdateModList();
            UpdateCatagories();

            CatagoriesComboBox.SelectedIndex = 0;
        }
Пример #22
0
        public void CachePlaylists()
        {
            localPlaylists = new List <LocalPlaylist>();
            playlists      = new List <PlaylistInfo>();

            FileInfo[] files = new DirectoryInfo(playlistsDir).GetFiles("*.json");
            if (files.Length == 0)
            {
                return;
            }

            int id = 0;

            foreach (FileInfo file in files)
            {
                LocalPlaylist playlist = JsonCommon.Load <LocalPlaylist>(file.FullName);
                playlist.ID = $"{id}";

                int trackId = 0;
                foreach (LocalTrack track in playlist.Tracks)
                {
                    track.ID = $"{id}:{trackId++}";
                }

                localPlaylists.Add(playlist);

                id++;
            }

            localPlaylists.ForEach(p => {
                playlists.Add(new PlaylistInfo {
                    Type  = ProviderType.Local,
                    ID    = p.ID,
                    Title = p.Title,
                    Cover = $"api/content/playlistCover?id={p.ID}"
                });
            });
        }
Пример #23
0
        private static ExcelConvertorSettings ProcessSettings(ExcelConvertorSettings settings)
        {
            if (settings == null)
            {
                return(new ExcelConvertorSettings());
            }

            var newMandatoryColumns = new List <string>();

            if (settings.MandatoryColumns.Any())
            {
                foreach (var smc in settings.MandatoryColumns)
                {
                    if (!string.IsNullOrWhiteSpace(smc) && !string.IsNullOrEmpty(smc))
                    {
                        newMandatoryColumns.Add(smc);
                    }
                }

                settings.MandatoryColumns = JsonCommon.ToCamelCase(newMandatoryColumns);
            }
            return(settings);
        }
Пример #24
0
        /// <summary>
        /// Инициализация списка закачек
        /// </summary>
        private void InitPumpsList()
        {
            Logger.WriteToTrace("Формирование списка закачек.");

            Pumps = new List <ETLProcess>();

            string[]      pumpConfigs = Directory.GetFiles(Context.Settings.Registry.ProgramsPath);
            List <string> ids         = new List <string>();

            foreach (string pumpConfig in pumpConfigs)
            {
                try
                {
                    string  fileName = Path.GetFileName(pumpConfig);
                    JObject data     = JsonCommon.Load(pumpConfig);
                    string  id       = data["id"].ToString();

                    // Если уже существует закачка с таким ID
                    if (ids.Contains(id))
                    {
                        Logger.WriteToTrace($"Закачка с ID = \"{id}\" (\"{fileName}\") уже существует.", TraceMessageKind.Warning);
                        continue;
                    }

                    // Процесс инициализируется данными конфигурации
                    ETLProcess prc = new ETLProcess(pumpConfig, Context.History);

                    // Сохраняется конфиг закачки с описанием
                    Pumps.Add(prc);
                    ids.Add(id);
                }
                catch (Exception ex)
                {
                    Logger.WriteToTrace($"Ошибка при формировании реестра закачек: {ex}.", TraceMessageKind.Error);
                }
            }
        }
Пример #25
0
        /// <summary>
        ///     Main function, the args arent used though
        /// </summary>
        /// <param name="args">dunno why these are here</param>
        public static void Main_DEPRECIATED(string[] args)
        {
            JsonCommon.OverrideModInstallerVariables();
            //exe check
            Console.WriteLine("Detecting if " + ModInstallerCommon.Files.execdir + " exists...");
            if (!File.Exists(ModInstallerCommon.Files.execdir) && !ModInstallerCommon.BypassExec)
            {
                ModInstallerCommon.throwexept("H3VR not found!");
                return;
            }

            Console.WriteLine("H3VR found!");
            //online check
            if (!NetCheck.isOnline(ModInstallerCommon.Pingsite))
            {
                ModInstallerCommon.throwexept("Cannot connect to github!");
                return;
            }

            Console.WriteLine("Welcome to the H3VR Mod installer!");
            Console.WriteLine("Please select the mod you would like to install using 'dl [modnamehere]' ");
            Console.WriteLine("ex: 'dl wurstmod'");
            Console.WriteLine("To see a list of downloadable mods, type 'modlists'");
            Console.WriteLine("To see a list of commands, type 'help' \n");
Start:
            var input = Console.ReadLine();

            var inputargs = input.Split(' ');

            Array.Resize(ref inputargs, 10); //ensures no "OUT OF INDEX TIME TO SHIT MYSELF REEEE"


            doCommand(inputargs);

            Console.WriteLine("");
            goto Start;
        }
Пример #26
0
        private JObject UserInfo(string token, ref string errMsg)
        {
            try
            {
                string result;

                using (var wc = new HttpClient())
                {
                    var response = wc.PostAsync(OpenidUrl, new StringContent("access_token=" + token)).Result;
                    result = response.Content.ReadAsStringAsync().Result;
                }

                result = result.Replace("callback(", string.Empty).Replace(");", string.Empty).Trim();

                var openid = JsonCommon.Deserialize(result).Value <string>("openid");

                using (var wc = new HttpClient())
                {
                    var response = wc.PostAsync(UserInfoUrl,
                                                new StringContent(string.Format(_userInfoUrlParams, openid, token))).Result;

                    result = response.Content.ReadAsStringAsync().Result;
                }

                var user = JsonCommon.Deserialize(result);

                user.Add("openid", openid);

                return(user);
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;

                return(null);
            }
        }
Пример #27
0
 public void AddComponent(Component component)
 {
     components.Add(component);
     Mana.Internal.SceneInterface.createComponent(name, JsonCommon.convertComponent(component).ToString());
 }
Пример #28
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            string method = context.Request.Params["method"];

            if ("list".Equals(method))
            {
                string ajax = context.Request.Params["ajax"];

                BrandProjectDAO dao = new BrandProjectDAO();
                BrandProject    bp  = new BrandProject();
                bp.bpType = context.Request.Params["bpType"];
                DataSet ds     = dao.select(bp);
                string  result = "";
                if (String.IsNullOrEmpty(ajax))
                {
                    result = "_list = " + JsonCommon.ds2json(ds);
                }
                else
                {
                    result = JsonCommon.ds2json(ds);
                }
                context.Response.Write(result);
            }
            else if ("detail".Equals(method))
            {
                BrandProjectDAO dao = new BrandProjectDAO();
                BrandProject    bp  = new BrandProject();
                bp.bpId = context.Request.Params["bpId"];
                DataSet ds   = dao.select(bp);
                string  json = JsonCommon.ds2json(ds);


                PictureDAO picDao = new PictureDAO();
                Picture    pic    = new Picture();
                pic.picTableName = "BrandProject";
                pic.picTableId   = bp.bpId;
                DataSet picDs   = picDao.select(pic);
                string  picJson = JsonCommon.ds2json(picDs);

                json = String.Format("[{0},{1}]", json, picJson);
                context.Response.Write(json);
            }
            else if ("save".Equals(method))
            {
                string          bpContent = HttpUtility.UrlDecode((context.Request.Params["bpContent"]).Replace("@", "%"));
                string          bpType    = context.Request.Params["bpType"];
                string          bpId      = context.Request.Params["bpId"];
                BrandProjectDAO dao       = new BrandProjectDAO();
                BrandProject    bp        = new BrandProject();
                bp.bpContent = bpContent;
                bp.bpType    = bpType;
                if (!String.IsNullOrEmpty(bpId))
                {
                    bp.bpId = bpId;
                    dao.update(bp);
                }
                else
                {
                    bp.bpId = Guid.NewGuid().ToString();
                    bpId    = bp.bpId;
                    dao.insert(bp);
                }


                string     pics   = context.Request.Params["pics"];
                string     disc   = context.Request.Params["disc"];
                PictureDAO picDao = new PictureDAO();

                //删除要删除的图片
                string delPics = context.Request.Params["delPic"];
                if (!String.IsNullOrEmpty(delPics))
                {
                    string[] arrDelPics = delPics.Split(',');
                    for (int i = 0; i < arrDelPics.Length; i++)
                    {
                        Picture p = new Picture();
                        p.picId = arrDelPics[i];
                        picDao.delete(p);
                    }
                }
                if (!String.IsNullOrEmpty(pics))
                {
                    string[] arrPics = pics.Split(',');
                    string[] arrDisc = disc.Split(',');
                    for (int i = 0; i < arrPics.Length; i++)
                    {
                        string fileName = arrPics[i].Substring(arrPics[i].LastIndexOf("/") + 1);
                        string fromPath = context.Server.MapPath(arrPics[i]);
                        string toPath   = context.Server.MapPath(FileHelper.Default_Pic_Forder + fileName);
                        FileHelper.MoveTo(fromPath, toPath);
                        Picture pic = new Picture();
                        pic.picTableId   = bpId;
                        pic.picTableName = "BrandProject";
                        pic.picDescrip   = arrDisc[i];
                        pic.picExtension = fileName.Substring(fileName.LastIndexOf(".") + 1);
                        pic.picName      = fileName;
                        pic.picPath      = FileHelper.Default_Pic_Forder + fileName;
                        picDao.insert(pic);
                    }
                }
            }
            else if ("delete".Equals(method))
            {
                string          bpId = context.Request.Params["bpId"];
                BrandProjectDAO dao  = new BrandProjectDAO();
                BrandProject    bp   = new BrandProject();
                bp.bpId = bpId;
                dao.delete(bp);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public string GetTechnologyContent()
        {
            // Declaring Log4Net
            log4net.ILog logger = log4net.LogManager.GetLogger(typeof(string));

            try
            {
                // Load All Content List
                string contentPath = System.Configuration.ConfigurationManager.AppSettings["TechnologyContentPath"].ToString();
                var    contentList = new JsonCommon().GetContentList(contentPath + "ContentList.json");
                if (contentList == null)
                {
                    return("OK");
                }

                foreach (var content in contentList)
                {
                    // Load Web Site
                    HtmlAgilityPack.HtmlNode.ElementsFlags["link"] = HtmlAgilityPack.HtmlElementFlag.Closed;
                    var htmlDoc = new HtmlCommon().LoadWeb(content.FeedAddress);
                    if (htmlDoc.DocumentNode == null)
                    {
                        return("OK");
                    }

                    // Collection of Article (Item) Node
                    HtmlAgilityPack.HtmlNodeCollection itemNode = htmlDoc.DocumentNode.SelectNodes(content.ItemNode);
                    if (itemNode == null)
                    {
                        return("OK");
                    }

                    // Create Post
                    foreach (HtmlAgilityPack.HtmlNode item in itemNode)
                    {
                        PostModel post = new PostModel();

                        // Link Assignment
                        post.Link = item.ChildNodes["link"].InnerText;
                        if (post.Link == null)
                        {
                            continue;
                        }

                        // Content Post List
                        var postList = new JsonCommon().GetPostList(contentPath + "PostList.json");
                        if (postList == null)
                        {
                            continue;
                        }

                        // Check Post is not Exist
                        if (postList.Exists(x => x.Link == post.Link) == true)
                        {
                            continue;
                        }

                        // Get Short Text
                        post.ShortArticle = new TextCommon().RemoveTags(item.ChildNodes["description"].InnerText);

                        // Load Article
                        HtmlAgilityPack.HtmlDocument articleDoc = new HtmlCommon().LoadWeb(post.Link);
                        if (articleDoc.DocumentNode == null)
                        {
                            continue;
                        }

                        post.Id = new TextCommon().UniqueId(content.Name);

                        post.Content = PostContentType.Photo;

                        post.Priority = PostPriorityType.Normal;

                        post.Category = PostCategoryType.Technology;

                        post.Photo = new HtmlCommon().DownloadFile(content.HaveRoot == "1" ? articleDoc.DocumentNode.SelectSingleNode(content.PostPhoto).GetAttributeValue("src", null) : content.WebAddress + articleDoc.DocumentNode.SelectSingleNode(content.PostPhoto).GetAttributeValue("src", null), contentPath + @"Media\" + post.Id + ".jpg");
                        if (post.Photo == null)
                        {
                            continue;
                        }

                        post.Voice = null;

                        post.Video = null;

                        post.Audio = null;

                        post.Caption = new TextCommon().RemoveSpace(articleDoc.DocumentNode.SelectSingleNode(content.PostCaption).InnerText);

                        post.Article = new TextCommon().RemoveTags(articleDoc.DocumentNode.SelectSingleNode(content.PostArticle).InnerText);

                        post.ArticleLength = new TextCommon().WordCount(post.Article);

                        post.ShortLink = new BitlyAPI().Shorten(post.Link, "bit.ly", "txt");
                        if (post.ShortLink == null)
                        {
                            continue;
                        }

                        post.GetDate = System.DateTime.Now.ToShortDateString();

                        post.GetTime = System.DateTime.Now.ToShortTimeString();

                        post.ArticlePhotoCount = null;

                        post.ArticleVideoCount = null;

                        post.CaptionWordCount = "0";

                        // Add To Content Black Post Queue
                        post.CaptionBlockWordCount = "0";
                        if (post.CaptionBlockWordCount.To <int>() > 0)
                        {
                            var addBlockPost = new JsonCommon().AddPost(contentPath + "BlockPostList.json", post);
                            if (addBlockPost == null)
                            {
                                continue;
                            }
                            continue;
                        }

                        // Add To Content Post Queue
                        var addPost = new JsonCommon().AddPost(contentPath + "PostList.json", post);
                        if (addPost == null)
                        {
                            continue;
                        }

                        // Add To Telegram Post Queue
                        var addTelegram = new TelegramPublish().AddTelegramQueue(post);
                        if (addTelegram == null)
                        {
                            continue;
                        }
                    }
                }
                return("OK");
            }
            catch (System.Exception ex)
            {
                logger.Error(ex.ToString());
                return(null);
            }
        }
Пример #30
0
        public void UpdateModList(string dispcat = "n/a")
        {
            DownloadableModsList.Items.Clear();
            InstalledModsList.Items.Clear();

            if (dispcat == "n/a")
            {
                dispcat = publicdispcat;
            }
            publicdispcat = dispcat;

            var totalmods = JsonCommon.GetAllMods();

            if (dispcat == "n/a")
            {
                dispcat = "dependencies";
            }

            Console.WriteLine(dispcat);

            var dispmods = JsonModList.GetDeserializedModListFormatOnline(dispcat).Modlist;

            var installedMods = H3VRModInstaller.Backend.JSON.InstalledMods.GetInstalledMods(); //f**k you

            ModFile[] list = null;

            var relevantint = 0;

            for (var i = 0; i < totalmods.Length; i++)
            {
                //this just checks if the mod we're working with is an installedmod, or a dl mod in isinstldmod
                var isinstldmod = false;
                var x           = 0;
                for (x = 0; x < installedMods.Length; x++)
                {
                    if (totalmods[i].ModId == installedMods[x].ModId)
                    {
                        isinstldmod = true;
                        break;
                    }
                }

                var isdispmod = false;
                for (int y = 0; y < dispmods.Length; y++)
                {
                    if (totalmods[i].ModId == dispmods[y].ModId)
                    {
                        isdispmod = true;
                        break;
                    }
                }

                //sets vars to installedmods or input
                if (isinstldmod)
                {
                    list        = installedMods;
                    relevantint = x;
                }
                else
                {
                    if (publicdispcat == "n/a")
                    {
                        goto Finish;
                    }
                    list        = totalmods;
                    relevantint = i;
                }


                var mod = new ListViewItem(list[relevantint].Name, 0); //0
                mod.SubItems.Add(list[relevantint].Version);           //1
                mod.SubItems.Add(list[relevantint].Author[0]);         //2
                mod.SubItems.Add(list[relevantint].Description);       //3
                mod.SubItems.Add(list[relevantint].ModId);             //4


                if (!isinstldmod && isdispmod)
                {
                    DownloadableModsList.Items.Add(mod);
                }
                if (isinstldmod)
                {
                    InstalledModsList.Items.Add(mod);
                }
                Finish :;
            }

            for (int i = 0; i < InstalledModsList.Items.Count; i++)
            {
                //if cached installed mod is a older version than the database
                if (new Version(InstalledModsList.Items[i].SubItems[1].Text).CompareTo(new Version(ModParsing.GetSpecificMod(InstalledModsList.Items[i].SubItems[4].Text).Version)) < 0)
                {
                    InstalledModsList.Items[i].BackColor = System.Drawing.Color.Yellow;
                }
            }
        }