//public static void Main(string[] args)
        //{

        //    var obj = new WBSSLStore.Scheduler.OrderUpdation.OrderUpdation(new Data.Infrastructure.DatabaseFactory());
        //    obj.FetchApiOrders();
        //    //obj.FetAPIOrderBySite();

        //}
        public void FetAPIOrderBySite()
        {
            try
            {
                if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["isUpdateCustomSite"]))
                {
                    string siteids  = System.Configuration.ConfigurationManager.AppSettings["CustomSiteid"].ToString();
                    var    _cussite = siteids.Split(new char[] { ',' }).ToArray();
                    var    Sites    = (from s in DbContext.Sites
                                       where s.isActive == true && _cussite.Contains(s.ID.ToString())
                                       select s).ToList();
                    foreach (Site s in Sites)
                    {
                        try
                        {
                            logger.Log("-----Start Custom Site Order Updating For :" + s.Alias + "-----", Logger.LogType.STATUSUPDATE);


                            FetchOrderThruRESTAPI(s);


                            logger.Log("-----End Custom Site Order Updating For :" + s.Alias + "-----", Logger.LogType.STATUSUPDATE);
                        }
                        catch (Exception ex)
                        {
                            logger.LogException(ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            { }
        }
Esempio n. 2
0
 /// <summary>
 /// Sends a message that a shard disconnected
 /// </summary>
 /// <param name="exception">The exception of the disconnected shard.</param>
 /// <param name="shard">The shard that got disconnected.</param>
 private async Task ShardDisconnectedAsync(Exception exception, DiscordSocketClient shard)
 {
     try
     {
         //Log.Warning($"<:RedStatus:519932993343586350> Shard: `{shard.ShardId}` Disconnected with the reason {exception.Message}").;
     }
     catch (Exception)
     {
         // Logs the message to a txt file if it was unable to send the message.
         _logger.LogException($"Shard: {shard.ShardId}", exception);
     }
 }
Esempio n. 3
0
 /// <summary>
 /// Sends a message that a shard disconnected
 /// </summary>
 /// <param name="exception">The exception of the disconnected shard.</param>
 /// <param name="shard">The shard that got disconnected.</param>
 private async Task ShardDisconnectedAsync(Exception exception, DiscordSocketClient shard)
 {
     try
     {
         var channel = _client.GetGuild(Convert.ToUInt64(ConfigData.Data.BaseServer)).GetTextChannel(Convert.ToUInt64(ConfigData.Data.ExceptionChannel));
         await channel.SendMessageAsync($"<:RedStatus:519932993343586350> Shard: `{shard.ShardId}` Disconnected with the reason {exception.Message}");
     }
     catch (Exception)
     {
         // Logs the message to a txt file if it was unable to send the message.
         _logger.LogException($"Shard: {shard.ShardId}", exception);
     }
 }
Esempio n. 4
0
        public async Task RemoveReadOnlyAsync()
        {
            if (await _adminService.HasCommandAccessAsync(Context.User, UserType.Owner))
            {
                try
                {
                    if (Directory.Exists(GlobalVars.CacheFolder))
                    {
                        DirectoryInfo users = new DirectoryInfo(GlobalVars.CacheFolder);
                    }


                    await ReplyAsync("Removed read only on all directories.");
                }
                catch (Exception e)
                {
                    _logger.LogException(Context.Message.Content, e);
                    await ReplyAsync("Unable to remove read only on all directories due to an internal error.");
                }
            }
        }
Esempio n. 5
0
        public List <StringBuilder> ImportProducts(List <Gateways.RestAPIModels.Response.ALLProduct> ProductList, Site site, decimal Margin)
        {
            ProductPricing resellerProductPricing = null;
            Contract       ClientContract         = GetClientContract(site.ID);
            StringBuilder  SuccessProduct         = new StringBuilder();
            StringBuilder  UnSuccessProduct       = new StringBuilder();

            var ProductSlugs = GeneralHelper.GetProductDetailSlugs();

            Contract resellerContract = _contract.Find(cn => cn.SiteID == site.ID && cn.isAutoCalculation == false && cn.isForReseller == true && cn.ContractLevel == null && cn.RecordStatusID != (int)RecordStatus.DELETED).OrderBy(cn => cn.ID).FirstOrDefault();

            if (resellerContract != null)
            {
                resellerProductPricing = _productPricing.Find(pp => pp.ContractID == resellerContract.ID && pp.SiteID == site.ID).FirstOrDefault();
            }



            foreach (Gateways.RestAPIModels.Response.ALLProduct apiProduct in ProductList)
            {
                try
                {
                    ProductPricingModel model = new ProductPricingModel();

                    var productavailablity = _productavailablity.Find(pro => pro.Product.InternalProductCode.Equals(apiProduct.ProductCode, StringComparison.OrdinalIgnoreCase) && pro.SiteID == site.ID && pro.Product.RecordStatusID != (int)RecordStatus.DELETED).EagerLoad(p => p.Product).FirstOrDefault();
                    var sl = ProductSlugs.Where(x => x.ProductCode.Equals(apiProduct.ProductCode, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

                    if (productavailablity == null)
                    {
                        //Create Product Row
                        Product objProduct = new Product();
                        apiProduct.Brand                       = apiProduct.Brand.ToLower() == "verisign" ? "symantec" : apiProduct.Brand;
                        objProduct.BrandID                     = GetBrand().Where(br => br.BrandName.Equals(apiProduct.Brand, StringComparison.OrdinalIgnoreCase)).FirstOrDefault().ID;
                        objProduct.CanbeReissued               = apiProduct.CanbeReissued;
                        objProduct.InternalProductCode         = apiProduct.ProductCode;
                        objProduct.isCompetitiveUpgradeAllowed = apiProduct.IsCompetitiveUpgradeSupported;
                        objProduct.isNoOfServerFree            = apiProduct.isNoOfServerFree;
                        objProduct.isSANEnabled                = apiProduct.IsSanEnable;
                        objProduct.isWildcard                  = apiProduct.IsWildCardProduct;
                        objProduct.ProductDescription          = apiProduct.ProductName;
                        objProduct.ProductName                 = apiProduct.ProductName;
                        objProduct.ProductTypeID               = apiProduct.ProductType;
                        objProduct.RecordStatusID              = (int)RecordStatus.ACTIVE;
                        objProduct.RefundDays                  = apiProduct.RefundDays;
                        objProduct.ReissueDays                 = apiProduct.ReissueDays;
                        objProduct.ReissueType                 = "Included";
                        objProduct.SanMax                      = apiProduct.SanMax;
                        objProduct.SanMin                      = apiProduct.SanMin;

                        objProduct.DetailPageslug = sl != null ? sl.SlugUrl : string.Empty;
                        model.product             = objProduct;

                        ProductAvailablity objAvailablity = new ProductAvailablity();
                        objAvailablity.isActive  = true;
                        objAvailablity.Product   = objProduct;
                        objAvailablity.SiteID    = site.ID;
                        model.productAvailablity = objAvailablity;

                        SuccessProduct.Append(SetMarginalPrice(model, apiProduct, site, Margin, ClientContract.ID, false));

                        //Add reseller pricing for default reseller contract
                        if (resellerContract != null && resellerProductPricing == null)
                        {
                            SetMarginalPrice(model, apiProduct, site, Margin, resellerContract.ID, false);
                        }
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(productavailablity.Product.DetailPageslug))
                        {
                            productavailablity.Product.DetailPageslug = sl != null ? sl.SlugUrl : string.Empty;
                        }

                        model.product            = productavailablity.Product;
                        model.productAvailablity = productavailablity;

                        model.Month_12 = _productPricing.Find(pp => pp.SiteID == site.ID && pp.ProductID == productavailablity.ProductID && pp.ContractID == ClientContract.ID && (pp.NumberOfMonths < 12 ? 12 : pp.NumberOfMonths) == (int)SettingConstants.NumberOfMonths.Month12).FirstOrDefault();
                        model.Month_24 = _productPricing.Find(pp => pp.SiteID == site.ID && pp.ProductID == productavailablity.ProductID && pp.ContractID == ClientContract.ID && pp.NumberOfMonths == (int)SettingConstants.NumberOfMonths.Month24).FirstOrDefault();

                        SuccessProduct.Append(SetMarginalPrice(model, apiProduct, site, Margin, ClientContract.ID, true));

                        //Add reseller pricing for default reseller contract
                        if (resellerContract != null && resellerProductPricing == null)
                        {
                            model.Month_12 = _productPricing.Find(pp => pp.SiteID == site.ID && pp.ContractID == resellerContract.ID && pp.ProductID == productavailablity.ProductID && pp.NumberOfMonths == (int)SettingConstants.NumberOfMonths.Month12).FirstOrDefault();
                            model.Month_24 = _productPricing.Find(pp => pp.SiteID == site.ID && pp.ContractID == resellerContract.ID && pp.ProductID == productavailablity.ProductID && pp.NumberOfMonths == (int)SettingConstants.NumberOfMonths.Month24).FirstOrDefault();
                            SetMarginalPrice(model, apiProduct, site, Margin, resellerContract.ID, true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Log("Error while importing product : " + (apiProduct != null ? apiProduct.ProductName : string.Empty), Logger.LogType.INFO);
                    _logger.LogException(ex);
                }
            }

            List <StringBuilder> lstReturn = new List <StringBuilder>();

            lstReturn.Add(SuccessProduct);
            lstReturn.Add(UnSuccessProduct);
            return(lstReturn);
        }
Esempio n. 6
0
        public TimerService(DiscordShardedClient client, Logger.Logger logger)
        {
            this._logger = logger;

            this._timer = new Timer(async _ =>
            {
                var random               = new Random();
                var randomAvatarMode     = random.Next(1, 4);
                var randomAvatarModeDesc = "";

                switch (randomAvatarMode)
                {
                case 1:
                    randomAvatarModeDesc = "Recent listens";
                    break;

                case 2:
                    randomAvatarModeDesc = "Weekly albums";
                    break;

                case 3:
                    randomAvatarModeDesc = "Monthly albums";
                    break;

                case 4:
                    randomAvatarModeDesc = "Overall albums";
                    break;
                }

                this._logger.Log($"Featured: Picked mode {randomAvatarMode} - {randomAvatarModeDesc}");

                try
                {
                    var lastFMUserName = await this._userService.GetRandomLastFMUserAsync();
                    this._logger.Log($"Featured: Picked user {lastFMUserName}");

                    switch (randomAvatarMode)
                    {
                    // Recent listens
                    case 1:
                        var tracks    = await this._lastFMService.GetRecentScrobblesAsync(lastFMUserName, 25);
                        var trackList = tracks
                                        .Select(s => new CensoredAlbum(s.ArtistName, s.AlbumName))
                                        .Where(w => !string.IsNullOrEmpty(w.AlbumName) &&
                                               !GlobalVars.CensoredAlbums.Select(s => s.ArtistName).Contains(w.ArtistName) &&
                                               !GlobalVars.CensoredAlbums.Select(s => s.AlbumName).Contains(w.AlbumName));

                        var currentTrack = trackList.First();

                        var albumImages = await this._lastFMService.GetAlbumImagesAsync(currentTrack.ArtistName, currentTrack.AlbumName);

                        this._trackString = $"{currentTrack.AlbumName} \n" +
                                            $"by {currentTrack.ArtistName} \n \n" +
                                            $"{randomAvatarModeDesc} from {lastFMUserName}";

                        this._logger.Log("Featured: Changing avatar to: " + this._trackString);

                        if (albumImages?.Large != null)
                        {
                            ChangeToNewAvatar(client, albumImages.Large.AbsoluteUri);
                        }
                        else
                        {
                            this._logger.Log("Featured: Album had no image, switching to alternative avatar mode");
                            goto case 3;
                        }

                        break;

                    // Weekly albums
                    case 2:
                    case 3:
                    case 4:
                        var timespan = LastStatsTimeSpan.Week;
                        switch (randomAvatarMode)
                        {
                        case 3:
                            timespan = LastStatsTimeSpan.Month;
                            break;

                        case 4:
                            timespan = LastStatsTimeSpan.Overall;
                            break;
                        }

                        var albums = await this._lastFMService.GetTopAlbumsAsync(lastFMUserName, timespan, 10);

                        if (!albums.Any())
                        {
                            this._logger.Log($"Featured: User {lastFMUserName} had no albums, switching to different user.");
                            lastFMUserName = await this._userService.GetRandomLastFMUserAsync();
                            albums         = await this._lastFMService.GetTopAlbumsAsync(lastFMUserName, timespan, 10);
                        }

                        var albumList = albums
                                        .Select(s => new CensoredAlbum(s.ArtistName, s.Name))
                                        .Where(w => !GlobalVars.CensoredAlbums.Select(s => s.ArtistName).Contains(w.ArtistName) &&
                                               !GlobalVars.CensoredAlbums.Select(s => s.AlbumName).Contains(w.AlbumName))
                                        .ToList();

                        var albumFound = false;
                        var i          = 0;

                        while (!albumFound)
                        {
                            var currentAlbum = albumList[i];

                            var albumImage = await this._lastFMService.GetAlbumImagesAsync(currentAlbum.ArtistName, currentAlbum.AlbumName);

                            this._trackString = $"{currentAlbum.AlbumName} \n" +
                                                $"by {currentAlbum.ArtistName} \n \n" +
                                                $"{randomAvatarModeDesc} from {lastFMUserName}";

                            if (albumImage?.Large != null)
                            {
                                this._logger.Log($"Featured: Album {i} success, changing avatar to: \n" +
                                                 $"{this._trackString}");

                                ChangeToNewAvatar(client, albumImage.Large.AbsoluteUri);
                                albumFound = true;
                            }
                            else
                            {
                                this._logger.Log($"Featured: Album {i} had no image, switching to alternative album");
                                i++;
                            }
                        }

                        break;
                    }
                }
                catch (Exception e)
                {
                    this._logger.LogException("ChangeFeaturedAvatar", e);
                }
            },
                                    null,
                                    TimeSpan.FromSeconds(Convert.ToDouble(Constants.BotWarmupTimeInSeconds)), // 4) Time that message should fire after the timer is created
                                    TimeSpan.FromMinutes(Convert.ToDouble(ConfigData.Data.TimerRepeat)));     // 5) Time after which message should repeat (use `Timeout.Infinite` for no repeat)

            this._internalStatsTimer = new Timer(async _ =>
            {
                logger.Log("Updating metrics and status");
                Statistics.DiscordServerCount.Set(client.Guilds.Count);
                Statistics.RegisteredUsers.Set(await this._userService.GetTotalUserCountAsync());
                Statistics.RegisteredGuilds.Set(await this._guildService.GetTotalGuildCountAsync());

                await client.SetGameAsync($"{ConfigData.Data.CommandPrefix} | {client.Guilds.Count} servers | fmbot.xyz");
            },
                                                 null,
                                                 TimeSpan.FromSeconds(Constants.BotWarmupTimeInSeconds + 10),
                                                 TimeSpan.FromMinutes(1));

            this._externalStatsTimer = new Timer(async _ =>
            {
                if (client.CurrentUser.Id.Equals(Constants.BotProductionId) && !string.IsNullOrEmpty(ConfigData.Data.DblApiToken))
                {
                    logger.Log("Updating top.gg server count");
                    var dblApi = new AuthDiscordBotListApi(Constants.BotProductionId, ConfigData.Data.DblApiToken);

                    try
                    {
                        var me = await dblApi.GetMeAsync();
                        await me.UpdateStatsAsync(client.Guilds.Count);
                    }
                    catch (Exception e)
                    {
                        logger.LogException("Exception while updating top.gg count!", e);
                    }
                }
                else
                {
                    logger.Log("Non-production bot found or top.gg token not entered, cancelling top.gg server count updater");
                    this._externalStatsTimer.Change(Timeout.Infinite, Timeout.Infinite);
                }
            },
                                                 null,
                                                 TimeSpan.FromSeconds(Constants.BotWarmupTimeInSeconds + 20),
                                                 TimeSpan.FromMinutes(5));

            this._timerEnabled = true;
        }
        public void SendMessage()
        {
            try
            {
                if (logger == null)
                {
                    logger = new Logger.Logger();
                }

                //logger.Log("-------Start Sending Mails:" + DateTime.Now + "-------", Logger.LogType.EMAILQUEUE);

                int iCount = 0, iMaxCount = Convert.ToInt16(ConfigurationManager.AppSettings["MaxNoOfTries"]);
                var emailqueues = objDbContext.EmailQueues.Where(e => e.Site.isActive == true && e.NumberOfTries <= iMaxCount).EagerLoad(x => x.SiteSMTP).OrderBy(e => e.NumberOfTries).ToList();
                if (objDbContext != null)
                {
                    if (_db != null)
                    {
                        _db.Dispose();
                        _db = null;
                    }
                    objDbContext.Dispose();
                    objDbContext = null;
                }
                foreach (EmailQueue email in emailqueues)
                {
                    try
                    {
                        context = prepareMessage(email);
                        SendMail(context, iCount);
                    }
                    catch (SmtpException smtpex)
                    {
                        email.LastAttempt      = DateTime.Now;
                        email.NumberOfTries    = context.domain.NumberOfTries + 1;
                        email.LastErrorMessage = (smtpex.Message.Length > 126 ? smtpex.Message.Substring(0, 125) : smtpex.Message);

                        //objDbContext.EmailQueues.Attach(email);
                        //objDbContext.Entry<EmailQueue>(email).State = System.Data.Entity.EntityState.Modified;

                        SaveinDB(iCount, email, false);
                    }
                    catch (Exception ex)
                    {
                        email.LastAttempt      = DateTime.Now;
                        email.NumberOfTries    = context.domain.NumberOfTries + 1;
                        email.LastErrorMessage = (ex.Message.Length > 126 ? ex.Message.Substring(0, 125) : ex.Message);

                        //objDbContext.EmailQueues.Attach(context.domain);
                        //objDbContext.Entry<EmailQueue>(context.domain).State = System.Data.Entity.EntityState.Modified;


                        logger.LogException(ex);

                        SaveinDB(iCount, email, false);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogException(ex);
            }
            finally
            {
                if (objDbContext != null)
                {
                    if (_db != null)
                    {
                        _db.Dispose();
                        _db = null;
                    }
                    objDbContext.Dispose();
                    objDbContext = null;
                }
                // logger.Log("-------End  Sending Mails:" + DateTime.Now + "-------", Logger.LogType.EMAILQUEUE);
            }
        }