Exemplo n.º 1
0
    public static string UrlSEO(string Text)
    {
        System.Globalization.CultureInfo cui = new System.Globalization.CultureInfo("en-US");

        string strReturn = System.Net.WebUtility.HtmlDecode(Text.Trim());

        strReturn = strReturn.Replace("ğ", "g");
        strReturn = strReturn.Replace("Ğ", "g");
        strReturn = strReturn.Replace("ü", "u");
        strReturn = strReturn.Replace("Ü", "u");
        strReturn = strReturn.Replace("ş", "s");
        strReturn = strReturn.Replace("Ş", "s");
        strReturn = strReturn.Replace("ı", "i");
        strReturn = strReturn.Replace("İ", "i");
        strReturn = strReturn.Replace("ö", "o");
        strReturn = strReturn.Replace("Ö", "o");
        strReturn = strReturn.Replace("ç", "c");
        strReturn = strReturn.Replace("Ç", "c");
        strReturn = strReturn.Replace(" - ", "+");
        strReturn = strReturn.Replace("-", "+");
        strReturn = strReturn.Replace(" ", "+");
        strReturn = strReturn.Trim();
        strReturn = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9+]").Replace(strReturn, "");
        strReturn = strReturn.Trim();
        strReturn = strReturn.Replace("+", "-");
        return(strReturn.ToLower(cui));
    }
Exemplo n.º 2
0
    public static string Replacement_Code(string Text)
    {
        try
        {
            string strReturn = Text.Trim();

            strReturn = strReturn.Replace("ğ", "g");
            strReturn = strReturn.Replace("Ğ", "G");
            strReturn = strReturn.Replace("ü", "u");
            strReturn = strReturn.Replace("Ü", "U");
            strReturn = strReturn.Replace("ş", "s");
            strReturn = strReturn.Replace("Ş", "S");
            strReturn = strReturn.Replace("ı", "i");
            strReturn = strReturn.Replace("İ", "I");
            strReturn = strReturn.Replace("ö", "o");
            strReturn = strReturn.Replace("Ö", "O");
            strReturn = strReturn.Replace("ç", "c");
            strReturn = strReturn.Replace("Ç", "C");
            strReturn = strReturn.Replace(".", "-");
            strReturn = strReturn.Replace("-", "+");
            strReturn = strReturn.Replace(" ", "+");

            strReturn = strReturn.Trim();
            strReturn = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9+]").Replace(strReturn, "");
            strReturn = strReturn.Trim();
            strReturn = strReturn.Replace("++", "-");
            strReturn = strReturn.Replace("+", "-");
            return(strReturn);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
Exemplo n.º 3
0
    public string KodOlustur(string Text)
    {
        string strReturn = Text.Trim();

        strReturn = strReturn.Replace("ğ", "g");
        strReturn = strReturn.Replace("Ğ", "G");
        strReturn = strReturn.Replace("ü", "u");
        strReturn = strReturn.Replace("Ü", "U");
        strReturn = strReturn.Replace("ş", "s");
        strReturn = strReturn.Replace("Ş", "S");
        strReturn = strReturn.Replace("ı", "i");
        strReturn = strReturn.Replace("İ", "I");
        strReturn = strReturn.Replace("ö", "o");
        strReturn = strReturn.Replace("Ö", "O");
        strReturn = strReturn.Replace("ç", "c");
        strReturn = strReturn.Replace("Ç", "C");
        strReturn = strReturn.Replace("-", "+");
        strReturn = strReturn.Replace(" ", "_");
        strReturn = strReturn.Replace("/", "//");
        strReturn = strReturn.Replace("'", "''");


        strReturn = strReturn.Trim();
        strReturn = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9+]").Replace(strReturn, "");
        strReturn = strReturn.Trim();
        strReturn = strReturn.Replace("+", "_");
        return(strReturn);
    }
Exemplo n.º 4
0
 protected override void ParseAdditionalInformation()
 {
     string bankName = new Regex(@"/BBK/.*\|?").Match(statementLine).Value;
     if (!string.IsNullOrEmpty(bankName))
     {
         bankName = bankName.Substring(5);
         if (bankName.EndsWith("|"))
         {
             bankName = bankName.Substring(0, bankName.Length - 1);
         }
         int vertical = bankName.IndexOf("|");
         if (-1 < vertical)
         {
             bankName = bankName.Substring(0, vertical);
         }
         bankStatement.CptyBankName = bankName.Trim();
     }
     AddInformation();
     //put tag 86 information to remark
     string[] remarks = statementLine.Split(new string[] { TAG_ADDITIONAL_INFO }, StringSplitOptions.None);
     if (remarks.Length > 1)
     {
         bankStatement.Remark = remarks[1];
     }
 }
Exemplo n.º 5
0
 /// <summary>
 /// Удаляет комментарии
 /// </summary>
 /// <param name="input"></param>
 /// <returns></returns>
 private string CleanUp(string input)
 {
     var copy = input;
     copy = new Regex("(/\\*(.|[\r\n])*?\\*/)|(//.*)")
                 .Replace(copy, "")
                 .Replace("\r", "")
                 .Replace("\n", "");
     return copy.Trim().ToLower();
 }
Exemplo n.º 6
0
        public string get(string video_id, string owner_id, string token, string AccountID, string GroupID)
        {
            string tmp = new PostAPI().post("https://api.vk.com/method/video.add", ("owner_id=" + owner_id + "&video_id=" + video_id + "&access_token=" + token), null, null, AccountID, GroupID);
            string s = new Regex("{\"response\":([0-9]+)}").Match(tmp).Groups[1].Value;

            //Возврат результатов и очистка ресурсов
            AccountID = null; GroupID = null; video_id = null; owner_id = null; token = null; tmp = null;
            return (s != null && s.Trim() != "" ? s : s = null);
        }
Exemplo n.º 7
0
        public static string get(string method, string argument, bool ResponseList = false)
        {
            string tmp = Browser.post("https://api.vk.com/method/" + method.Trim(), argument.Replace(" ", "").Trim()).Trim();
            string response = new Regex("^{\"response\":\\[(.+)\\]}$").Match(tmp).Groups[1].Value;

            //На случай ошибки, мы вернем данные об ошибке вместо нужных параметров
            if (response.Trim() != "")
                return (ResponseList ? tmp : response);
            else
                return tmp;
        }
Exemplo n.º 8
0
 public string ToText()
 {
     if (string.IsNullOrEmpty(text))
     {
         return string.Empty;
     }
     else
     {
         string txt = new Regex(@"\{\*?\\[^{}]+}|[{}]|\\\n?[A-Za-z]+\n?(?:-?\d+)?[ ]?").Replace(text, "");
         return txt.Trim().Replace("\n", "<br>");
     }
 }
Exemplo n.º 9
0
        public string get(string token)
        {
            int CountRefresh = 0;
            Refresh: string tmp = new PostAPI().post("https://api.vk.com/method/users.get", ("&access_token=" + token), null, null, null, null).Replace("\\/", "/").Replace(" ", "").ToLower().Trim();
            string id = new Regex("\"uid\":([0-9]+),?\"").Match(tmp).Groups[1].Value;

            //Проверка на капчу и получение URL
            if ((new Regex("userauthorizationfailed:invalidaccess_token").Match(tmp)).Success || CountRefresh == 3)
            {
                Console.WriteLine("Error UserGet.cs: {0}\nToken: {1}\nНажмите любую клавишу для завершения программы.", new Regex("\"error_msg\":\"([^\"]+)\"").Match(tmp).Groups[1].Value, token);
                Console.ReadKey();
                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
            else if ((id == null || id.Trim() == "") && CountRefresh != 3)
            {
                id = null; tmp = null; CountRefresh++; goto Refresh;
            }

            //Чистим ресурсы
            tmp = null; token = null;
            return id.Trim();
        }
Exemplo n.º 10
0
        public static string GetTextBetween(this string source, string endText, params string[] startText)
        {
            int startIndex = GetIndexAfter(source, startText);
            if (startIndex < 0) return null;

            int endIndex = source.IndexOf(endText, startIndex);
            if (endIndex < 0) throw new Exception(endText + " not found in string: " + source);

            string text = source.Substring(startIndex, endIndex - startIndex);

            // trim
            text = new Regex("&nbsp;").Replace(text, " ");
            text = text.Trim();

            return text;
        }
Exemplo n.º 11
0
 public string UrlClear(string metin)
 {
     try
     {
         char   tırnak    = '"';
         string strReturn = metin.Trim();
         strReturn = strReturn.Replace("ğ", "g");
         strReturn = strReturn.Replace("Ğ", "G");
         strReturn = strReturn.Replace("ü", "u");
         strReturn = strReturn.Replace("Ü", "U");
         strReturn = strReturn.Replace("ş", "s");
         strReturn = strReturn.Replace("Ş", "S");
         strReturn = strReturn.Replace("ı", "i");
         strReturn = strReturn.Replace("İ", "I");
         strReturn = strReturn.Replace("ö", "o");
         strReturn = strReturn.Replace("Ö", "O");
         strReturn = strReturn.Replace("ç", "c");
         strReturn = strReturn.Replace("Ç", "C");
         strReturn = strReturn.Replace("-", "+");
         strReturn = strReturn.Replace(" ", "-");
         strReturn = strReturn.Replace("'", "");
         strReturn = strReturn.Replace("%", "");
         strReturn = strReturn.Replace("<", "");
         strReturn = strReturn.Replace(">", "");
         strReturn = strReturn.Replace("?", "");
         strReturn = strReturn.Replace("!", "");
         strReturn = strReturn.Replace(":", "");
         strReturn = strReturn.Replace("/", "");
         strReturn = strReturn.Replace("\"", "-");
         strReturn = strReturn.Replace(".", "-");
         strReturn = strReturn.Replace(tırnak.ToString(), "");
         strReturn = strReturn.Trim();
         strReturn = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9+]").Replace(strReturn, "");
         strReturn = strReturn.Trim();
         strReturn = strReturn.Replace("+", "-");
         return(strReturn.ToLower());
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Exemplo n.º 12
0
        public string get(string token, string gPost)
        {
            int CountRefresh = 0;
            Refresh: string tmp = new PostAPI().post("https://api.vkontakte.ru/method/photos.getWallUploadServer", ("group_id=" + gPost.Replace("-", "").Trim() + "&access_token=" + token), null, null, null, null).Replace("\\/", "/").Trim();
            string url = new Regex("\"upload_url\":\"([^\"]+)\"").Match(tmp).Groups[1].Value;

            //Проверка на капчу и получение URL
            if ((new Regex("userauthorizationfailed:invalidaccess_token").Match(tmp.ToLower().Replace(" ", ""))).Success || CountRefresh == 3)
            {
                Console.WriteLine("Error UploadURL.cs: {0}\nToken: {1}\nНажмите любую клавишу для завершения программы.", new Regex("\"error_msg\":\"([^\"]+)\"").Match(tmp).Groups[1].Value, token);
                Console.ReadKey();
                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
            else if ((url == null || url.Trim() == "") && CountRefresh != 3)
            {
                url = null; tmp = null; CountRefresh++; goto Refresh;
            }

            //Чистим ресурсы
            tmp = null; token = null; gPost = null;
            return url;
        }
Exemplo n.º 13
0
    public static string De_Replacement_Code(string Text)
    {
        try
        {
            string strReturn = Text.Trim();


            strReturn = strReturn.Replace("-", ".");
            strReturn = strReturn.Replace("+", "-");
            strReturn = strReturn.Replace("+", " ");

            strReturn = strReturn.Trim();
            strReturn = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9+]").Replace(strReturn, "");
            strReturn = strReturn.Trim();
            strReturn = strReturn.Replace("-", "+");
            return(strReturn);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public static string UrlDonustur(string Yazi)
    {
        try
        {
            string strSonuc = ToLowerFonksiyonu(Yazi.Trim());

            strSonuc = strSonuc.Replace("-", "+");
            strSonuc = strSonuc.Replace(" ", "+");

            strSonuc = strSonuc.Replace("ç", "c");
            strSonuc = strSonuc.Replace("Ç", "C");

            strSonuc = strSonuc.Replace("ğ", "g");
            strSonuc = strSonuc.Replace("Ğ", "G");

            strSonuc = strSonuc.Replace("ı", "i");
            strSonuc = strSonuc.Replace("I", "İ");

            strSonuc = strSonuc.Replace("ö", "o");
            strSonuc = strSonuc.Replace("Ö", "O");

            strSonuc = strSonuc.Replace("ş", "s");
            strSonuc = strSonuc.Replace("Ş", "S");

            strSonuc = strSonuc.Replace("ü", "u");
            strSonuc = strSonuc.Replace("Ü", "U");

            strSonuc = strSonuc.Trim();
            strSonuc = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9+]").Replace(strSonuc, "");
            strSonuc = strSonuc.Trim();
            strSonuc = strSonuc.Replace("+", "-");
            return(strSonuc);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
Exemplo n.º 15
0
        public static IReader CreateReader(string email, string password, string source)
        {
            LogWriter.CreateLogfile();
            Settings.Default.authToken = "";
            const string authUrl = GOOGLE_LOGIN_ADDRESS;

            var reader = new Reader(source);

            string response = HttpClient.SendPostRequest(authUrl, new
            {

                service = "reader",
                Email = email,
                Passwd = password,
                source="DesktopGoogleReader",
                accountType = "GOOGLE"
            }, false);

            LogWriter.WriteTextToLogFile("Response from Google");
            LogWriter.WriteTextToLogFile(response);

            string authToken = "";

            try
            {
                LogWriter.WriteTextToLogFile("Trying to get Auth Token");
                authToken = new Regex(@"Auth=(?<authToken>\S+)").Match(response).Result("${authToken}");
                LogWriter.WriteTextToLogFile("AuthToken is " + authToken);
                Settings.Default.authToken = authToken.Trim();
            }
            catch (Exception e)
            {
                LogWriter.WriteTextToLogFile(e);
                throw new ArgumentException("AuthToken parsing error: " + e.Message);
            }

            return reader;
        }
Exemplo n.º 16
0
        public string basliktemizlesimdi(string baslik)
        {
            baslik = Regex.Replace(baslik, @"\'", string.Empty);
            baslik = baslik.ToString().ToLower();

            if (baslik.Length > 50)
            {
                baslik = baslik.Substring(0, 49) + "..";
            }

            baslik = baslik.Replace("'", "-");

            string strReturn = baslik.Trim();

            strReturn = strReturn.Replace("ğ", "g");
            strReturn = strReturn.Replace("Ğ", "g");
            strReturn = strReturn.Replace("ü", "u");
            strReturn = strReturn.Replace("Ü", "u");
            strReturn = strReturn.Replace("ş", "s");
            strReturn = strReturn.Replace("Ş", "s");
            strReturn = strReturn.Replace("ı", "i");
            strReturn = strReturn.Replace("İ", "i");
            strReturn = strReturn.Replace("ö", "o");
            strReturn = strReturn.Replace("Ö", "o");
            strReturn = strReturn.Replace("ç", "c");
            strReturn = strReturn.Replace("Ç", "c");
            strReturn = strReturn.Replace("-", "+");
            strReturn = strReturn.Replace(" ", "+");
            strReturn = strReturn.Trim();
            strReturn = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9+]").Replace(strReturn, "");
            strReturn = strReturn.Trim();
            strReturn = strReturn.Replace("+", "-");


            return(strReturn);
        }
Exemplo n.º 17
0
        ModData LoadModFromZip(string zipFileFullName)
        {
            log.Debug("Loading '{0}'", Path.GetFileName(zipFileFullName));

            ModData detail = new ModData();
            string tempDir = Path.Combine(Path.GetTempPath(), "mc", Guid.NewGuid().ToString());

            detail.FullPath = zipFileFullName;
            detail.FileSize = new FileInfo(zipFileFullName).Length;
            detail.Hash = new FileInfo(zipFileFullName).CalcMD5();

            // Fallback title
            detail.Title = Path.GetFileNameWithoutExtension(detail.FileName).ToLowerInvariant();
            detail.Title = detail.Title.ReplaceEx(new string[] { "aaa_", "zzz_", "aaa", "zzz" }, string.Empty);

            // Make any word begin with upercase letter
            detail.Title = Regex.Replace(detail.Title, @"((?<=\p{Ll})\p{Lu})|((?!\A)\p{Lu}(?>\p{Ll}))", " $0");

            // Remove duplicate spaces
            detail.Title.Normalize();

            try
            {
                Directory.CreateDirectory(tempDir);

                if (Unzip(zipFileFullName, tempDir, new string[] { MOD_DESC_FILENAME }, true, true))
                {
                    StringBuilder sb = new StringBuilder();

                    // Clear comments, cause they are often not wellformed
                    foreach (string line in File.ReadAllLines(Path.Combine(tempDir, MOD_DESC_FILENAME)))
                    {
                        string currentLine = new Regex("(?s)<!--.*?-->", RegexOptions.Compiled).Replace(line, "");
                        currentLine = new Regex("[&]+", RegexOptions.Compiled).Replace(line, "");

                        if (string.IsNullOrEmpty(currentLine))
                            continue;

                        sb.AppendLine(currentLine.Trim());
                    }

                    try
                    {
                        XmlReaderSettings settings = new XmlReaderSettings();

                        using (TextReader txtReader = new StringReader(sb.ToString()))
                        using (XmlReader reader = XmlReader.Create(txtReader, settings))
                        {
                            XmlDocument doc = new XmlDocument();
                            doc.Load(reader);

                            detail.Title = doc.GetInnerTextNormalized(string.Format("/modDesc/title/{0}", "de"));
                            if (string.IsNullOrEmpty(detail.Title))
                                detail.Title = doc.GetInnerTextNormalized("modDesc/title/en");

                            detail.Description = doc.GetInnerTextNormalized(string.Format("/modDesc/description/{0}", "de"));
                            if (string.IsNullOrEmpty(detail.Description))
                                detail.Description = doc.GetInnerTextNormalized("modDesc/description/en");

                            detail.Author = doc.GetInnerTextNormalized("/modDesc/author");
                            detail.Version = doc.GetInnerTextNormalized("/modDesc/version");
                            detail.IsMultiplayerReady = Convert.ToBoolean(doc.GetInnerTextSave("/modDesc/multiplayer/@supported"));

                            //lock (locker)
                            //{
                            //detail.Image = LoadBitmap(zipFileFullName, tempDir, doc.GetInnerTextSave("/modDesc/iconFilename"));
                            //}

                            foreach (XmlNode node in doc.SelectNodes("/modDesc/storeItems/storeItem"))
                            {
                                StoreItemData shopItem = new StoreItemData();

                                shopItem.Name = node.GetInnerTextSave(string.Format("{0}/name", "de"));
                                if (string.IsNullOrEmpty(shopItem.Name))
                                    shopItem.Name = node.GetInnerTextSave("en/name");

                                shopItem.Price = Convert.ToDouble(node.GetInnerTextSave("price"));
                                shopItem.Upkeep = Convert.ToDouble(node.GetInnerTextSave("dailyUpkeep"));
                                shopItem.MachineType = node.GetInnerTextSave("machineType");
                                shopItem.Brand = node.GetInnerTextSave("brand");

                                shopItem.Description = node.GetInnerTextSave(string.Format("{0}/description", "de"));
                                if (string.IsNullOrEmpty(shopItem.Description))
                                    shopItem.Description = node.GetInnerTextSave("en/description");

                                shopItem.Description = shopItem.Description.Replace("\r\n", " ");

                                //shopItem.IsMultiplayerReady = Convert.ToBoolean(node.GetInnerTextSave("/modDesc/multiplayer/@supported"));
                                shopItem.XmlFileName = node.GetInnerTextSave("xmlFilename");
                                shopItem.ImagePath = node.GetInnerTextSave("image/@active");
                                shopItem.BrandImagePath = node.GetInnerTextSave("image/@brand");

                                lock (locker)
                                {
                                    if (detail.Image == null)
                                    {
                                        detail.Image = LoadBitmap(zipFileFullName, tempDir, shopItem.ImagePath);
                                        shopItem.Image = detail.Image;
                                    }
                                    else
                                    {
                                        shopItem.Image = LoadBitmap(zipFileFullName, tempDir, shopItem.ImagePath);
                                    }

                                    shopItem.BrandImage = LoadBitmap(zipFileFullName, tempDir, shopItem.BrandImagePath);
                                }

                                detail.StoreItems.Add(shopItem);
                            }

                            doc = null;
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("Error while loading {0}".Args(zipFileFullName), ex);
                    }

                    if (detail.Image == null)
                    {
                        detail.Image = null;//Resources.NoPicture;
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("Error while loadings mod: " + zipFileFullName, ex);
            }
            finally
            {
                Directory.Delete(tempDir, true);
            }

            return detail;
        }
Exemplo n.º 18
0
 /// <summary>
 /// Removes invalid characters from the provided displayname.
 /// </summary>
 /// <param name="s"></param>
 /// <returns></returns>
 public static string RemoveInvalidCharacters(string s)
 {
     // NOTE: changing this code requires a change in RemoveInvalidCharacters, GetNoAccents javascript functions in SN.ContentName.js, in order that these work in accordance
     var noaccents = GetNoAccents(s);
     noaccents = new Regex(RepositoryPath.InvalidNameCharsPattern).Replace(noaccents, ContentNamingHelper.PlaceholderSymbol.ToString());
     // space is also removed
     noaccents = noaccents.Replace(' ', ContentNamingHelper.PlaceholderSymbol);
     // '-' should not be followed by another '-'
     noaccents = new Regex(ContentNamingHelper.PlaceholderSymbol + "{2,}").Replace(noaccents, ContentNamingHelper.PlaceholderSymbol.ToString());
     noaccents = noaccents.Trim(ContentNamingHelper.PlaceholderSymbol);
     return noaccents;
 }
Exemplo n.º 19
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            Icon = Resources.PortableApps_purple_64;
            MaximumSize = Screen.FromHandle(Handle).WorkingArea.Size;
#if !x86
            Text += @" (64-bit)";
#endif
            _formText = Text;
            Lang.SetControlLang(this);
            for (var i = 0; i < appsList.Columns.Count; i++)
                appsList.Columns[i].Text = Lang.GetText($"columnHeader{i + 1}");
            for (var i = 0; i < appsList.Groups.Count; i++)
                appsList.Groups[i].Header = Lang.GetText(appsList.Groups[i].Name);

            showColorsCheck.Left = showGroupsCheck.Right + 4;
            highlightInstalledCheck.Left = showColorsCheck.Right + 4;

            MessageBoxEx.TopMost = true;

            var internetIsAvailable = _ipv4 = NetEx.InternetIsAvailable();
            if (!internetIsAvailable)
            {
                internetIsAvailable = _ipv6 = NetEx.InternetIsAvailable(true);
                if (internetIsAvailable)
                    MessageBoxEx.Show(Lang.GetText("InternetProtocolWarningMsg"), _formText, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            if (!internetIsAvailable)
            {
                if (!UpdateSearch)
                    MessageBoxEx.Show(Lang.GetText("InternetIsNotAvailableMsg"), _formText, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Environment.ExitCode = 1;
                Application.Exit();
                return;
            }

            if (!UpdateSearch)
                _notifyBox.Show(Lang.GetText("DatabaseAccessMsg"), _formText, NotifyBox.NotifyBoxStartPosition.Center);

            // Get 'Si13n7.com' download mirrors
            var dnsInfo = new Dictionary<string, Dictionary<string, string>>();
            for (var i = 0; i < 3; i++)
            {
                if (!_ipv4 && _ipv6)
                {
                    dnsInfo = Ini.ReadAll(Resources.IPv6DNS, false);
                    break;
                }
                dnsInfo = Ini.ReadAll(NetEx.Transfer.DownloadString("https://raw.githubusercontent.com/Si13n7/_ServerInfos/master/DnsInfo.ini"), false);
                if (dnsInfo.Count == 0 && i < 2)
                {
                    Thread.Sleep(1000);
                    continue;
                }
                break;
            }
            if (dnsInfo.Count > 0)
                foreach (var section in dnsInfo.Keys)
                    try
                    {
                        var addr = dnsInfo[section][_ipv4 ? "addr" : "ipv6"];
                        if (string.IsNullOrEmpty(addr))
                            continue;
                        var domain = dnsInfo[section]["domain"];
                        if (string.IsNullOrEmpty(domain))
                            continue;
                        bool ssl;
                        bool.TryParse(dnsInfo[section]["ssl"], out ssl);
                        domain = ssl ? $"https://{domain}" : $"http://{domain}";
                        if (!_internalMirrors.ContainsEx(domain))
                            _internalMirrors.Add(domain);
                    }
                    catch (KeyNotFoundException) { }
                    catch (Exception ex)
                    {
                        Log.Write(ex);
                    }

            if (!UpdateSearch && _internalMirrors.Count == 0)
            {
                MessageBoxEx.Show(Lang.GetText("NoServerAvailableMsg"), _formText, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Environment.ExitCode = 1;
                Application.Exit();
                return;
            }

            // Encrypt host access data with AES-256 (safety ofc not guaranteed)
            if (!string.IsNullOrEmpty(_swSrv) && !string.IsNullOrEmpty(_swUsr) && !string.IsNullOrEmpty(_swPwd))
                try
                {
                    var winId = Win32_OperatingSystem.SerialNumber;
                    if (string.IsNullOrWhiteSpace(winId))
                        throw new PlatformNotSupportedException();
                    var aesPw = winId.EncryptToSha256();
                    if (_swSrv.StartsWithEx("http://", "https://"))
                    {
                        Ini.Write("Host", "Srv", _swSrv.EncryptToAes256(aesPw).EncodeToBase85());
                        Ini.Write("Host", "Usr", _swUsr.EncryptToAes256(aesPw).EncodeToBase85());
                        Ini.Write("Host", "Pwd", _swPwd.EncryptToAes256(aesPw).EncodeToBase85());
                    }
                    else
                    {
                        _swSrv = _swSrv.DecodeByteArrayFromBase85().DecryptFromAes256(aesPw).FromByteArrayToString();
                        _swUsr = _swUsr.DecodeByteArrayFromBase85().DecryptFromAes256(aesPw).FromByteArrayToString();
                        _swPwd = _swPwd.DecodeByteArrayFromBase85().DecryptFromAes256(aesPw).FromByteArrayToString();
                    }
                }
                catch (Exception ex)
                {
                    Log.Write(ex);
                }

            // Enforce database reset in certain cases
            var tmpAppsDbDir = Path.Combine(TmpDir, PathEx.GetTempDirName());
            var tmpAppsDbPath = Path.Combine(tmpAppsDbDir, "update.ini");
            var appsDbLastWriteTime = DateTime.Now.AddHours(1d);
            long appsDbLength = 0;
            if (!File.Exists(tmpAppsDbPath) && File.Exists(AppsDbPath))
                try
                {
                    var fi = new FileInfo(AppsDbPath);
                    appsDbLastWriteTime = fi.LastWriteTime;
                    appsDbLength = fi.Length;
                }
                catch (Exception ex)
                {
                    Log.Write(ex);
                }
            if (UpdateSearch || File.Exists(tmpAppsDbPath) || (DateTime.Now - appsDbLastWriteTime).TotalHours >= 1d || appsDbLength < 0x2a000 || (_appsDbSections = Ini.GetSections(AppsDbPath)).Count < 400)
                try
                {
                    if (File.Exists(AppsDbPath))
                        File.Delete(AppsDbPath);
                }
                catch (Exception ex)
                {
                    Log.Write(ex);
                }
            try
            {
                if (!File.Exists(AppsDbPath))
                {
                    if (!Directory.Exists(tmpAppsDbDir))
                        Directory.CreateDirectory(tmpAppsDbDir);

                    // Get internal app database
                    for (var i = 0; i < 3; i++)
                    {
                        NetEx.Transfer.DownloadFile(_ipv4 ? "https://raw.githubusercontent.com/Si13n7/PortableAppsSuite/master/AppInfo.ini" : $"{_internalMirrors[0]}/Downloads/Portable%20Apps%20Suite/.free/AppInfo.ini", AppsDbPath);
                        if (!File.Exists(AppsDbPath))
                        {
                            if (i > 1)
                                throw new InvalidOperationException("Server connection failed.");
                            Thread.Sleep(1000);
                            continue;
                        }
                        break;
                    }

                    // Get external app database
                    var externDbPath = Path.Combine(tmpAppsDbDir, "AppInfo.7z");
                    string[] externDbSrvs =
                    {
                        "Downloads/Portable%20Apps%20Suite/.free/PortableAppsInfo.7z",
                        "portableapps.com/updater/update.7z"
                    };
                    var internCheck = false;
                    foreach (var srv in externDbSrvs)
                    {
                        long length = 0;
                        if (!internCheck)
                        {
                            internCheck = true;
                            foreach (var mirror in _internalMirrors)
                            {
                                string tmpSrv = $"{mirror}/{srv}";
                                if (!NetEx.FileIsAvailable(tmpSrv))
                                    continue;
                                NetEx.Transfer.DownloadFile(tmpSrv, externDbPath);
                                if (!File.Exists(externDbPath))
                                    continue;
                                length = new FileInfo(externDbPath).Length;
                                if (File.Exists(externDbPath) && length > 0x6000)
                                    break;
                            }
                        }
                        else
                        {
                            NetEx.Transfer.DownloadFile(srv, externDbPath);
                            if (File.Exists(externDbPath))
                                length = new FileInfo(externDbPath).Length;
                        }
                        if (File.Exists(externDbPath) && length > 0x6000)
                            break;
                    }

                    // Merge databases
                    _appsDbSections = Ini.GetSections(AppsDbPath);
                    if (File.Exists(externDbPath))
                    {
                        using (var p = Compaction.Zip7Helper.Unzip(externDbPath, tmpAppsDbDir))
                            if (!p?.HasExited == true)
                                p?.WaitForExit();
                        File.Delete(externDbPath);
                        externDbPath = tmpAppsDbPath;
                        if (File.Exists(externDbPath))
                        {
                            foreach (var section in Ini.GetSections(externDbPath))
                            {
                                if (_appsDbSections.ContainsEx(section) || section.ContainsEx("PortableApps.com", "ByPortableApps"))
                                    continue;
                                var nam = Ini.Read(section, "Name", externDbPath);
                                if (string.IsNullOrWhiteSpace(nam) || nam.ContainsEx("jPortable Launcher"))
                                    continue;
                                if (!nam.StartsWithEx("jPortable", "PortableApps.com"))
                                {
                                    var tmp = new Regex(", Portable Edition|Portable64|Portable", RegexOptions.IgnoreCase).Replace(nam, string.Empty);
                                    tmp = Regex.Replace(tmp, @"\s+", " ");
                                    if (!string.IsNullOrWhiteSpace(tmp) && tmp != nam)
                                        nam = tmp.Trim().TrimEnd(',');
                                }
                                var des = Ini.Read(section, "Description", externDbPath);
                                if (string.IsNullOrWhiteSpace(des))
                                    continue;
                                var cat = Ini.Read(section, "Category", externDbPath);
                                if (string.IsNullOrWhiteSpace(cat))
                                    continue;
                                var ver = Ini.Read(section, "DisplayVersion", externDbPath);
                                if (string.IsNullOrWhiteSpace(ver))
                                    continue;
                                var pat = Ini.Read(section, "DownloadPath", externDbPath);
                                pat = $"{(string.IsNullOrWhiteSpace(pat) ? "http://downloads.sourceforge.net/portableapps" : pat)}/{Ini.Read(section, "DownloadFile", externDbPath)}";
                                if (!pat.EndsWithEx(".paf.exe"))
                                    continue;
                                var has = Ini.Read(section, "Hash", externDbPath);
                                if (string.IsNullOrWhiteSpace(has))
                                    continue;
                                var phs = new Dictionary<string, List<string>>();
                                foreach (var lang in Lang.GetText("availableLangs").Split(','))
                                {
                                    if (string.IsNullOrWhiteSpace(lang))
                                        continue;
                                    var tmpFile = Ini.Read(section, $"DownloadFile_{lang}", externDbPath);
                                    if (string.IsNullOrWhiteSpace(tmpFile))
                                        continue;
                                    var tmphash = Ini.Read(section, $"Hash_{lang}", externDbPath);
                                    if (string.IsNullOrWhiteSpace(tmphash) || !string.IsNullOrWhiteSpace(tmphash) && tmphash == has)
                                        continue;
                                    var tmpPath = Ini.Read(section, "DownloadPath", externDbPath);
                                    tmpFile = $"{(string.IsNullOrWhiteSpace(tmpPath) ? "http://downloads.sourceforge.net/portableapps" : tmpPath)}/{tmpFile}";
                                    phs.Add(lang, new List<string> { tmpFile, tmphash });
                                }
                                var siz = Ini.ReadLong(section, "InstallSize", 1, externDbPath);
                                var adv = Ini.Read(section, "Advanced", externDbPath);
                                File.AppendAllText(AppsDbPath, Environment.NewLine);
                                Ini.Write(section, "Name", nam, AppsDbPath);
                                Ini.Write(section, "Description", des, AppsDbPath);
                                Ini.Write(section, "Category", cat, AppsDbPath);
                                Ini.Write(section, "Version", ver, AppsDbPath);
                                Ini.Write(section, "ArchivePath", pat, AppsDbPath);
                                Ini.Write(section, "ArchiveHash", has, AppsDbPath);
                                if (phs.Count > 0)
                                {
                                    Ini.Write(section, "AvailableArchiveLangs", phs.Keys.Join(","), AppsDbPath);
                                    foreach (var item in phs)
                                    {
                                        Ini.Write(section, $"ArchivePath_{item.Key}", item.Value[0], AppsDbPath);
                                        Ini.Write(section, $"ArchiveHash_{item.Key}", item.Value[1], AppsDbPath);
                                    }
                                }
                                Ini.Write(section, "InstallSize", siz, AppsDbPath);
                                if (adv.EqualsEx("true"))
                                    Ini.Write(section, "Advanced", true, AppsDbPath);
                            }
                            try
                            {
                                Directory.Delete(tmpAppsDbDir, true);
                            }
                            catch (Exception ex)
                            {
                                Log.Write(ex);
                            }
                        }

                        // Add another external app database for unpublished stuff - requires host access data
                        if (!string.IsNullOrEmpty(_swSrv) && !string.IsNullOrEmpty(_swUsr) && !string.IsNullOrEmpty(_swPwd))
                            try
                            {
                                var externDb = NetEx.Transfer.DownloadString($"{_swSrv}/AppInfo.ini", _swUsr, _swPwd);
                                if (!string.IsNullOrWhiteSpace(externDb))
                                    File.AppendAllText(AppsDbPath, $@"{Environment.NewLine}{externDb}");
                            }
                            catch (Exception ex)
                            {
                                Log.Write(ex);
                            }

                        // Done with database
                        File.WriteAllText(AppsDbPath, File.ReadAllText(AppsDbPath).FormatNewLine());

                        // Get available apps
                        _appsDbSections = Ini.GetSections(AppsDbPath);
                        if (_appsDbSections.Count == 0)
                            throw new InvalidOperationException("No available apps found.");
                    }
                }
                if (!UpdateSearch)
                {
                    if (File.Exists(AppsDbPath))
                        AppsList_SetContent(_appsDbSections);
                    if (appsList.Items.Count == 0)
                        throw new InvalidOperationException("No available apps found.");
                    return;
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                if (!UpdateSearch)
                    MessageBoxEx.Show(Lang.GetText("NoServerAvailableMsg"), _formText, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Environment.ExitCode = 1;
                Application.Exit();
                return;
            }

            // Search updates
            try
            {
                var outdatedApps = new List<string>();
                foreach (var dir in GetInstalledApps(!string.IsNullOrEmpty(_swSrv) && !string.IsNullOrEmpty(_swUsr) && !string.IsNullOrEmpty(_swPwd) ? 3 : 0))
                {
                    var section = Path.GetFileName(dir);
                    if (Ini.ReadBoolean(section, "NoUpdates"))
                        continue;
                    if (dir.ContainsEx("\\.share\\"))
                        section = $"{section}###";
                    if (!_appsDbSections.ContainsEx(section))
                        continue;
                    var fileData = new Dictionary<string, string>();
                    var verData = Ini.Read(section, "VersionData", AppsDbPath);
                    var verHash = Ini.Read(section, "VersionHash", AppsDbPath);
                    if (!string.IsNullOrWhiteSpace(verData) && !string.IsNullOrWhiteSpace(verHash))
                    {
                        if (!verData.Contains(","))
                            verData = $"{verData},";
                        var verDataSplit = verData.Split(',');
                        if (!verHash.Contains(","))
                            verHash = $"{verHash},";
                        var verHashSplit = verHash.Split(',');
                        if (verDataSplit.Length != verHashSplit.Length)
                            continue;
                        for (var i = 0; i < verDataSplit.Length; i++)
                        {
                            if (string.IsNullOrWhiteSpace(verDataSplit[i]) || string.IsNullOrWhiteSpace(verHashSplit[i]))
                                continue;
                            fileData.Add(verDataSplit[i], verHashSplit[i]);
                        }
                    }
                    if (fileData.Count > 0)
                    {
                        if (fileData.Select(data => new { data, filePath = Path.Combine(dir, data.Key) })
                                    .Where(x => File.Exists(x.filePath))
                                    .Where(x => Crypto.EncryptFileToSha256(x.filePath) != x.data.Value)
                                    .Select(x => x.data).Any())
                            if (!outdatedApps.ContainsEx(section))
                                outdatedApps.Add(section);
                        continue;
                    }
                    if (dir.ContainsEx("\\.share\\"))
                        continue;
                    var appIniPath = Path.Combine(dir, "App\\AppInfo\\appinfo.ini");
                    if (!File.Exists(appIniPath))
                        continue;
                    var localVer = Ini.ReadVersion("Version", "DisplayVersion", appIniPath);
                    var serverVer = Ini.ReadVersion(section, "Version", AppsDbPath);
                    if (localVer >= serverVer)
                        continue;
                    Log.Write($"Update for '{section}' found (Local: '{localVer}'; Server: '{serverVer}').");
                    if (!outdatedApps.ContainsEx(section))
                        outdatedApps.Add(section);
                }
                if (outdatedApps.Count == 0)
                    throw new WarningException("No updates available.");
                AppsList_SetContent(outdatedApps);
                if (MessageBoxEx.Show(string.Format(Lang.GetText("UpdatesAvailableMsg"), appsList.Items.Count, appsList.Items.Count > 1 ? Lang.GetText("UpdatesAvailableMsg1") : Lang.GetText("UpdatesAvailableMsg2")), _formText, MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) != DialogResult.Yes)
                    throw new WarningException("Update canceled.");
                foreach (ListViewItem item in appsList.Items)
                    item.Checked = true;
            }
            catch (WarningException ex)
            {
                Log.Write(ex.Message);
                Environment.ExitCode = 0;
                Application.Exit();
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                Environment.ExitCode = 1;
                Application.Exit();
            }
        }
Exemplo n.º 20
0
        private string UploadCAPCHA(string url)
        {
            try
            {
                //Типа разделитель и данные для работы
                string str = DateTime.Now.Ticks.ToString("x");
                byte[] boundary = Encoding.UTF8.GetBytes("\n--" + str + "\n");
                HttpWebRequest request = null;
                Stream stream = null, StreamHTML = null;
                StreamReader Reader = null;
                WebClient wc = new WebClient();
                WebResponse response = null;
                string result = null;

                try
                {
                    //Создаем подключение с URL для загрузки картинок
                    request = (HttpWebRequest)WebRequest.Create("http://antigate.com/in.php");
                    request.ContentType = "multipart/form-data; boundary=" + str;
                    request.Method = "POST";
                    request.KeepAlive = true;
                    request.MaximumAutomaticRedirections = 3;
                    request.ReadWriteTimeout = 1000 * 30;
                    request.Timeout = 1000 * 30;

                    //Хедеры
                    byte[] image = wc.DownloadData(url);
                    byte[] header = Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"method\"\n\npost\n--{0}\n", str) +
                                                           string.Format("Content-Disposition: form-data; name=\"key\"\n\n{0}\n--{1}\n", conf.KeyAntigate, str) +
                                                           "Content-Disposition: form-data; name=\"file\"; filename=\"image.jpg\"\nContent-Type: \"image/jpg\"\n\n");

                    //Записываем в поток все данные
                    stream = request.GetRequestStream();
                    stream.Write(boundary, 0, boundary.Length);
                    stream.Write(header, 0, header.Length);
                    stream.Write(image, 0, image.Length);
                    stream.Write(boundary, 0, boundary.Length);
                    image = null; header = null;

                    //Возвращаем данные
                    response = request.GetResponse();
                    StreamHTML = response.GetResponseStream();
                    Reader = new StreamReader(StreamHTML);
                    result = new Regex(@"ok\|([0-9]+)").Match(Reader.ReadToEnd().ToLower()).Groups[1].Value;
                }
                catch { }
                finally
                {
                    //Чистим ресурсы
                    url = null; wc.Dispose(); wc = null; str = null; boundary = null;
                    if (Reader != null)
                    {
                        Reader.Close(); Reader.Dispose(); Reader = null;
                    }
                    if (StreamHTML != null)
                    {
                        StreamHTML.Close(); StreamHTML.Dispose(); StreamHTML = null;
                    }
                    if (response != null)
                    {
                        response.Close(); response.Dispose(); response = null;
                    }
                    if (stream != null)
                    {
                        stream.Close(); stream.Dispose(); stream = null;
                    }
                    if (request != null)
                    {
                        request.Abort(); request = null;
                    }
                }

                //Возвращаем результат
                return result != null ? (result.Trim() == "" ? null : result.Trim()) : null;
            }
            catch
            {
                return (url = null);
            }
        }
Exemplo n.º 21
0
        public LoadConf()
        {
            //Загрузка ключей и другого мусора
            if(File.Exists(conf.DirConf))
            {
                string s = File.ReadAllText(conf.DirConf).Replace(" ", "");
                conf.KeyAntigate = new Regex("KeyAntigate:([^;]+);").Match(s).Groups[1].Value;
                s = null;
            }

            //Загрузка данных по аккаунтам и группам
            foreach (string AccountDir in Directory.GetFiles(conf.DirAccount))
            {
                string account = Regex.Replace(Regex.Replace(File.ReadAllText(AccountDir), @"/\*[^\*]+\*/", ""), "//[^\n\r]+\n?\r?", "").Replace("\r", "").Replace("\n", "").Replace(@"\", "");
                if (account.Replace(" ", "").Trim() == "")
                    continue;

                //Смотрим нужно ли грабить задание или нет
                string activ = new Regex("activ:([a-z]+);").Match(account.Replace(" ", "").ToLower()).Groups[1].Value.Trim();
                if (activ == "" || activ == "false")
                    continue;

                //Токены и ID
                string Token = new Regex("UsrerToken:([a-zA-Z0-9]+);").Match(account.Replace(" ", "")).Groups[1].Value;
                string ModToken = new Regex("ModerationToken:([a-zA-Z0-9]+);").Match(account.Replace(" ", "")).Groups[1].Value;
                string userID = new engine.VK_API.UserGet().get(Token);
                string ModID = new engine.VK_API.UserGet().get(ModToken);
                string ID = new Regex("id:([^;]+);").Match(account.Replace(" ", "")).Groups[1].Value.Trim();

                ////////////////////////////////////////////////////////////////////////////////////////////////////////

                //Список групп куда грабить и список URL для загрузки изображения
                List<InfoClass.GroupPost> Gpost = new List<InfoClass.GroupPost> { };
                foreach (string gPost in new Regex("grouppost:{([-0-9,]+)};").Match(account.Replace(" ", "").ToLower()).Groups[1].Value.Split(','))
                {
                    //Добовляем в List
                    Gpost.Add(new InfoClass.GroupPost
                    {
                        GroupID = gPost.Trim(),
                        UploadURL = new engine.VK_API.UploadURL().get(Token, gPost),
                        ModerationUploadURL = new engine.VK_API.UploadURL().get(ModToken, gPost)
                    });
                }

                ////////////////////////////////////////////////////////////////////////////////////////////////////////

                //Грузим ключи если они доступны
                List<string> key = new List<string> { };
                foreach (string s1 in new Regex("GroupKey:{([A-Za-z-0-9,_-]+)};").Match(account.Replace(" ", "")).Groups[1].Value.Split(','))
                {
                    if (File.Exists(conf.DirKey + s1))
                    {
                        foreach (string s2 in File.ReadLines(conf.DirKey + s1))
                        {
                            key.Add(s2.Trim());
                        }
                    }
                }

                ////////////////////////////////////////////////////////////////////////////////////////////////////////

                //Грузим теги если они доступны
                List<string> tag = new List<string> { };
                if (File.Exists(conf.DirTag + ID))
                {
                    foreach (string s in File.ReadLines(conf.DirTag + ID))
                    {
                        tag.Add(s.ToLower().Trim());
                    }
                }

                ////////////////////////////////////////////////////////////////////////////////////////////////////////

                //Загружаем данные для групп
                List<InfoClass.GroupList> Glist = new List<InfoClass.GroupList> { };
                foreach (string gListID in new Regex("GroupList:{([a-zA-Z0-9-_,]+)};").Match(account.Replace(" ", "")).Groups[1].Value.Split(','))
                {
                    if (File.Exists(conf.DirGroupList + gListID))
                    {
                        foreach (string gList in Regex.Replace(Regex.Replace(File.ReadAllText(conf.DirGroupList + gListID), @"/\*[^\*]+\*/", ""), "//[^\n\r]+\n?\r?", "").ToLower().Replace(" ", "").Replace("\r", "").Split('\n'))
                        {
                            if (gList.Trim() == "")
                                continue;

                            GroupCollection g = new Regex("group:'([-0-9]+)',{photo=([a-z]+),text=([a-z]+),poll=([a-z]+),audio=([a-z]+),video=([a-z]+),break=([a-z]+),attachmentsnullblock=([a-z]+),moderationnews=([a-z]+)};").Match(gList).Groups;
                            int lastTime = 0;

                            //Если нету ID откуда брать то и остальное не нужно
                            if (g[1].Value.Replace(" ", "").Trim() == "")
                                continue;

                            ////////////////////////////////////////////////////////////////////

                            if (File.Exists(conf.DirLastTime + ID))
                            {
                                foreach (string last in File.ReadAllLines(conf.DirLastTime + ID))
                                {
                                    if ((new Regex(g[1].Value + ":[0-9]+").Match(last)).Success)
                                    {
                                        lastTime = int.Parse(new Regex(g[1].Value + ":([0-9]+)").Match(last).Groups[1].Value);
                                        break;
                                    }
                                }
                            }

                            ////////////////////////////////////////////////////////////////////

                            Glist.Add(new InfoClass.GroupList
                            {
                                GroupID = g[1].Value,
                                photo = g[2].Value == "true" ? true : false,
                                text = g[3].Value == "true" ? true : false,
                                poll = g[4].Value == "true" ? true : false,
                                audio = g[5].Value == "true" ? true : false,
                                video = g[6].Value == "true" ? true : false,
                                BreakMedia = g[7].Value == "true" ? true : false,
                                AttachmentsNullBlock = g[8].Value == "true" ? true : false,
                                ModerationNews = g[9].Value == "true" ? true : false,
                                LastTime = lastTime
                            });
                            g = null;
                        }
                    }
                }

                ////////////////////////////////////////////////////////////////////////////////////////////////////////

                //Загружаем Hash фотографий
                List<ulong> Hphoto = new List<ulong> { };
                if (File.Exists(conf.DirHashPhoto + ID))
                    foreach (string hash in File.ReadAllLines(conf.DirHashPhoto + ID))
                    {
                        try
                        {
                            Hphoto.Add(ulong.Parse(hash.Trim()));
                        }
                        catch { }
                    }

                ////////////////////////////////////////////////////////////////////////////////////////////////////////

                //Стоп слова
                List<string> SWords = new List<string> { };
                if (File.Exists(conf.DirStopWords))
                {
                    foreach (string s1 in new Regex("StopWords:{([^)]+)};").Match(account.Replace(" ", "")).Groups[1].Value.Split(','))
                    {
                        foreach (string s2 in File.ReadLines(conf.DirStopWords))
                        {
                            if ((new Regex(@"id:" + s1.ToLower() + "={([^}]+)}").Match(s2.ToLower())).Success)
                                foreach (string s3 in new Regex("id:[a-zA-Z-0-9-_]+={([^}]+)}").Match(s2).Groups[1].Value.Split(','))
                                {
                                    SWords.Add(s3.Trim());
                                }
                        }
                    }
                }

                ////////////////////////////////////////////////////////////////////////////////////////////////////////

                //Данные по ключам
                string Ktext = new Regex("keytext:{true,'count:([0-9]+)'};").Match(account.Replace(" ", "").ToLower()).Groups[1].Value.Trim();
                string Kwall = new Regex("keywall:{true,'count:([0-9]+)'};").Match(account.Replace(" ", "").ToLower()).Groups[1].Value.Trim();
                string Kphoto = new Regex("keyphoto:{true,'count:([0-9]+)'};").Match(account.Replace(" ", "").ToLower()).Groups[1].Value.Trim();
                string Kvideo = new Regex("keyvideo:{true,'count:([0-9]+)'};").Match(account.Replace(" ", "").ToLower()).Groups[1].Value.Trim();
                string Rstart = new Regex("random:([0-9]+),([0-9]+);").Match(account.Replace(" ", "").ToLower()).Groups[1].Value.Trim();
                string Rnext = new Regex("random:([0-9]+),([0-9]+);").Match(account.Replace(" ", "").ToLower()).Groups[2].Value.Trim();
                string Keyaes = new Regex("AES:{true,'([^']+)'};").Match(account.Replace(" ", "")).Groups[1].Value;
                GroupCollection gUtext = new Regex("Url:{[trueTRUE]+,'([^']+)'};").Match(account).Groups;

                ////////////////////////////////////////////////////////////////////////////////////////////////////////

                //Добовляем все данные
                conf.account.Add(new InfoClass.account
                {
                    id = ID,
                    UserID = userID,
                    ModerationID = ModID,
                    token = Token,
                    ModerationToken = ModToken,
                    activ = new Regex("activ:([a-z]+);").Match(account.Replace(" ", "").ToLower()).Groups[1].Value.Trim() == "true" ? true : false,
                    GroupPost = Gpost,
                    GroupKey = key.Count == 0 ? null : key,
                    GroupList = Glist,
                    HashPhoto = Hphoto,
                    KeyText = int.Parse(Ktext == "" ? "0" : Ktext),
                    KeyWall = int.Parse(Kwall == "" ? "0" : Kwall),
                    KeyPhoto = int.Parse(Kphoto == "" ? "0" : Kphoto),
                    KeyVideo = int.Parse(Kvideo == "" ? "0" : Kvideo),
                    StopWords = SWords.Count == 0 ? null : SWords,
                    Tag = tag,
                    RandomStart = int.Parse(Rstart == "" ? "0" : Rstart),
                    RandomNext = int.Parse(Rnext == "" ? "0" : Rnext),
                    ReplaceTag = new Regex("replacetag:([trueTRUE]+);").Match(account.Replace(" ", "").ToLower()).Groups[1].Value.Trim() == "true" ? true : false,
                    UploadPhoto = new Regex("uploadphoto:([trueTRUE]+);").Match(account.Replace(" ", "").ToLower()).Groups[1].Value.Trim() == "true" ? true : false,
                    AddVideo = new Regex("addvideo:([trueTRUE]+);").Match(account.Replace(" ", "").ToLower()).Groups[1].Value.Trim() == "true" ? true : false,
                    CreateDescVideo = new Regex("createdescvideo:([trueTRUE]+);").Match(account.Replace(" ", "").ToLower()).Groups[1].Value.Trim() == "true" ? true : false,
                    KeyAES = Keyaes.Trim() == "" ? null : Keyaes.Trim(),
                    URL_Text = gUtext[1].Value.ToString().Trim() != "" ? gUtext[1].Value.ToString().Replace("<br>", "\n") : null
                });

                ////////////////////////////////////////////////////////////////////////////////////////////////////////

                //Чистим ресурсы
                Gpost = null; key = null; Glist = null; Hphoto = null; SWords = null; gUtext = null; ModID = null; ID = null; Keyaes = null; userID = null;
                Kwall = null; Kphoto = null; Kvideo = null; Rstart = null; Rnext = null; ModToken = null; Token = null; tag = null; Ktext = null;
            }
        }
Exemplo n.º 22
0
    /// <summary>
    /// Create the filename for the recording 
    /// </summary>
    /// <param name="recordingPath"></param>
    public void MakeFileName(string recordingPath)
    {
      TvBusinessLayer layer = new TvBusinessLayer();

      Setting setting;
      if (!IsSerie)
      {
        Log.Debug("Scheduler: MakeFileName() using \"moviesformat\" (_isSerie={0})", _isSerie);
        setting = layer.GetSetting("moviesformat", "%title%");
      }
      else
      {
        Log.Debug("Scheduler: MakeFileName() using \"seriesformat\" (_isSerie={0})", _isSerie);
        setting = layer.GetSetting("seriesformat", "%title%");
      }

      string strInput = "title%";
      if (setting != null)
      {
        if (setting.Value != null)
        {
          strInput = setting.Value;
        }
      }
      string subDirectory = string.Empty;
      string fullPath = recordingPath;
      string fileName;
      const string recEngineExt = ".ts";

      string[] TagNames = {
                            "%channel%",
                            "%title%",
                            "%name%",
                            "%series%",
                            "%episode%",
                            "%part%",
                            "%date%",
                            "%start%",
                            "%end%",
                            "%genre%",
                            "%startday%",
                            "%startmonth%",
                            "%startyear%",
                            "%starthh%",
                            "%startmm%",
                            "%endday%",
                            "%endmonth%",
                            "%endyear%",
                            "%endhh%",
                            "%endmm%"
                          };
      string[] TagValues = {
                             _schedule.ReferencedChannel().DisplayName.Trim(),
                             Program.Title.Trim(),
                             Program.EpisodeName.Trim(),
                             Program.SeriesNum.Trim(),
                             Program.EpisodeNum.Trim(),
                             Program.EpisodePart.Trim(),
                             Program.StartTime.ToString("yyyy-MM-dd"),
                             Program.StartTime.ToShortTimeString(),
                             Program.EndTime.ToShortTimeString(),
                             Program.Genre.Trim(),
                             Program.StartTime.ToString("dd"),
                             Program.StartTime.ToString("MM"),
                             Program.StartTime.ToString("yyyy"),
                             Program.StartTime.ToString("HH"),
                             Program.StartTime.ToString("mm"),
                             Program.EndTime.ToString("dd"),
                             Program.EndTime.ToString("MM"),
                             Program.EndTime.ToString("yyyy"),
                             Program.EndTime.ToString("HH"),
                             Program.EndTime.ToString("mm")
                           };

      for (int i = 0; i < TagNames.Length; i++)
      {
        strInput = Utils.ReplaceTag(strInput, TagNames[i], Utils.MakeFileName(TagValues[i]), "unknown");
        if (!strInput.Contains("%"))
        {
          break;
        }
      }

      int index = strInput.LastIndexOf('\\');
      if (index != -1)
      {
        subDirectory = strInput.Substring(0, index).Trim();
        fileName = strInput.Substring(index + 1).Trim();
      }
      else
        fileName = strInput.Trim();


      if (subDirectory != string.Empty)
      {
        subDirectory = Utils.RemoveTrailingSlash(subDirectory);
        subDirectory = Utils.MakeDirectoryPath(subDirectory);

        /* Replace any trailing dots in path name; Bugfix for Mantis 1881 */
        subDirectory = new Regex(@"\.*$").Replace(subDirectory, "");
        /* Replace any trailing spaces in path name; Bugfix for Mantis 2933*/
        subDirectory = new Regex(@"\s+\\\s*|\\\s+").Replace(subDirectory, "\\");

        fullPath = recordingPath + "\\" + subDirectory.Trim();
        if (!System.IO.Directory.Exists(fullPath))
          System.IO.Directory.CreateDirectory(fullPath);
      }
      if (fileName == string.Empty)
      {
        DateTime dt = Program.StartTime;
        fileName = String.Format("{0}_{1}_{2}{3:00}{4:00}{5:00}{6:00}p{7}{8}",
                                 _schedule.ReferencedChannel().DisplayName, Program.Title,
                                 dt.Year, dt.Month, dt.Day,
                                 dt.Hour,
                                 dt.Minute,
                                 DateTime.Now.Minute, DateTime.Now.Second);
      }
      fileName = Utils.MakeFileName(fileName);
      if (DoesFileExist(fullPath + "\\" + fileName))
      {
        int i = 1;
        while (DoesFileExist(fullPath + "\\" + fileName + "_" + i))
          ++i;
        fileName += "_" + i;
      }
      _fileName = fullPath + "\\" + fileName + recEngineExt;
    }