Пример #1
0
        private void ProcessGeraden(string[] args, PublicMessageEventArgs e, string whatisit, Func <GeradenWoord, string> groupByMember, Func <GeradenWoord, DateTime> whenMember, Func <GeradenWoord, string> nameMember, Func <GeradenWoord, bool> filter)
        {
            var collection = GetGeradenWoordCollection();

            TimeSpan ago      = TimeSpan.Zero;
            string   agoParam = "4w";
            string   numParam = "42";

            if (args.Length >= 1)
            {
                agoParam = args[0];
            }

            if (args.Length >= 2)
            {
                numParam = args[1];
            }

            try
            {
                ago = TimeUtils.ParseTimeSpan(agoParam);
            }
            catch (FormatException)
            {
                Client.SendMessageToChat(e.Message.Chat.ID, $"Ik snap er niks van. Wat bedoel je met '{MessageUtils.HtmlEscape(agoParam)}'? Probeer eens '5d', '8u', '4w' of doe gek met '3w2d7u'.", "HTML", true);
                return;
            }

            if (!Int32.TryParse(numParam, out int number))
            {
                Client.SendMessageToChat(e.Message.Chat.ID, $"Ik snap er niks van. Wat bedoel je met '{MessageUtils.HtmlEscape(agoParam)}'? Hoe moet ik daar een getal van maken?", "HTML", true);
                return;
            }

            if (number == 0 || ago == TimeSpan.Zero)
            {
                Client.SendMessageToChat(e.Message.Chat.ID, $"Haha, erg grappig 👏 Hier zijn je nul resultaten, malloot.", "HTML", true);
                return;
            }

            var filteredCollection   = collection.Find(x => filter(x) && whenMember(x) >= (DateTime.UtcNow - ago));
            var aggregatedCollection = filteredCollection.GroupBy(groupByMember).Select(cl => new ResultLine {
                Name = nameMember(cl.First()), Count = cl.Count()
            });
            var sortedAggregatedCollection = aggregatedCollection.OrderByDescending(x => x.Count).Take(number);

            if (sortedAggregatedCollection.Count() < number)
            {
                number = sortedAggregatedCollection.Count();
            }
            StringBuilder result = new StringBuilder();

            result.AppendLine($"Top <b>{number}</b> {whatisit} vanaf <b>{TimeService.AsDutchString(DateTime.Now - ago)}</b>:");
            int place = 1;

            foreach (var record in sortedAggregatedCollection)
            {
                result.AppendLine($"{place}: {record.Name.TrimStart().TrimStart('@')} ({record.Count})");
                place++;
            }
            result.AppendLine($"<i>Totaal aantal records in deze periode: {filteredCollection.Count()} voor {aggregatedCollection.Count()} personen</i>");

            Client.SendMessageToChat(e.Message.Chat.ID, $"{result}", "HTML", disableWebPagePreview: true, disableNotification: true);
        }
Пример #2
0
 protected void btnok_Click(object sender, System.EventArgs e)
 {
     if (base.Action.Equals(ActionType.Add.ToString()) && !base.IsAuthorizedOp(ActionType.Add.ToString()))
     {
         base.ShowMsg("Không có thẩm quyền");
     }
     else if (base.Action.Equals(ActionType.Modify.ToString()) && !base.IsAuthorizedOp(ActionType.Modify.ToString()))
     {
         base.ShowMsg("Không có thẩm quyền");
     }
     else
     {
         AccountInfo accountInfo = new AccountInfo();
         if (base.IsEdit)
         {
             accountInfo = SinGooCMS.BLL.Account.GetDataById(base.OpID);
         }
         string @string = WebUtils.GetString(this.TextBox2.Text);
         if (accountInfo.AccountName != "superadmin")
         {
             accountInfo.AccountName = WebUtils.GetString(this.TextBox1.Text);
         }
         accountInfo.Email         = WebUtils.GetString(this.TextBox3.Text);
         accountInfo.Mobile        = WebUtils.GetString(this.TextBox4.Text);
         accountInfo.AutoTimeStamp = System.DateTime.Now;
         if (string.IsNullOrEmpty(accountInfo.AccountName))
         {
             base.ShowMsg("帐户名称不能为空");
         }
         else
         {
             if (base.Action.Equals(ActionType.Add.ToString()))
             {
                 if (string.IsNullOrEmpty(@string))
                 {
                     base.ShowMsg("帐户密码不为空");
                     return;
                 }
                 accountInfo.Password = DEncryptUtils.SHA512Encrypt(@string);
                 accountInfo.IsSystem = false;
                 if (SinGooCMS.BLL.Account.Add(accountInfo) > 0)
                 {
                     PageBase.log.AddEvent(base.LoginAccount.AccountName, "添加角色[" + accountInfo.AccountName + "] thành công");
                     MessageUtils.DialogCloseAndParentReload(this);
                 }
                 else
                 {
                     base.ShowMsg("添加角色失败");
                 }
             }
             if (base.Action.Equals(ActionType.Modify.ToString()))
             {
                 if (!string.IsNullOrEmpty(@string))
                 {
                     accountInfo.Password = DEncryptUtils.SHA512Encrypt(@string);
                 }
                 if (SinGooCMS.BLL.Account.Update(accountInfo))
                 {
                     PageBase.log.AddEvent(base.LoginAccount.AccountName, "修改角色[" + accountInfo.AccountName + "] thành công");
                     MessageUtils.DialogCloseAndParentReload(this);
                 }
                 else
                 {
                     base.ShowMsg("修改角色失败");
                 }
             }
         }
     }
 }
Пример #3
0
        Widget _buildNotificationTitle()
        {
            var type     = this.notification.type;
            var data     = this.notification.data;
            var subTitle = new TextSpan();
            var content  = "";

            if (type == "project_liked")
            {
                subTitle = new TextSpan(
                    " 赞了你的文章",
                    CTextStyle.PLargeBody2
                    );
            }

            if (type == "project_message_commented")
            {
                if (data.parentComment.isNotEmpty())
                {
                    content  = $" “{MessageUtils.AnalyzeMessage(data.parentComment, this.mentions, false)}”";
                    subTitle = new TextSpan(
                        " 回复了你的评论" + content,
                        CTextStyle.PLargeBody2
                        );
                }
                else
                {
                    subTitle = new TextSpan(
                        " 评论了你的文章",
                        CTextStyle.PLargeBody2
                        );
                }
            }

            if (type == "project_participate_comment")
            {
                if (data.parentComment.isNotEmpty())
                {
                    content = $" “{MessageUtils.AnalyzeMessage(data.parentComment, this.mentions, false)}”";
                }

                subTitle = new TextSpan(
                    " 回复了你的评论" + content,
                    CTextStyle.PLargeBody2
                    );
            }

            if (type == "project_message_liked")
            {
                if (data.comment.isNotEmpty())
                {
                    content = $" “{MessageUtils.AnalyzeMessage(data.comment, this.mentions, false)}”";
                }

                subTitle = new TextSpan(
                    " 赞了你的评论" + content,
                    CTextStyle.PLargeBody2
                    );
            }

            if (type == "project_message_participate_liked")
            {
                if (data.comment.isNotEmpty())
                {
                    content = $" “{MessageUtils.AnalyzeMessage(data.comment, this.mentions, false)}”";
                }

                subTitle = new TextSpan(
                    " 赞了你的评论" + content,
                    CTextStyle.PLargeBody2
                    );
            }

            return(new Column(
                       crossAxisAlignment: CrossAxisAlignment.start,
                       children: new List <Widget> {
                new RichText(
                    maxLines: 2,
                    text: new TextSpan(
                        children: new List <TextSpan> {
                    new TextSpan(
                        data.fullname,
                        CTextStyle.PLargeMedium
                        ),
                    subTitle
                }
                        ),
                    overflow: TextOverflow.ellipsis
                    ),
                new Text(
                    data.projectTitle,
                    maxLines: 1,
                    style: CTextStyle.PLargeMedium,
                    overflow: TextOverflow.ellipsis
                    )
            }
                       ));
        }
Пример #4
0
        /// <summary>
        /// Starts and adds a new vote to a server
        /// </summary>
        /// <param name="voteTitle"></param>
        /// <param name="voteDescription"></param>
        /// <param name="lastTime"></param>
        /// <param name="yesEmoji"></param>
        /// <param name="noEmoji"></param>
        /// <param name="guild"></param>
        /// <param name="channel"></param>
        /// <param name="userWhoExecuted"></param>
        /// <returns></returns>
        public static async Task StartVote(string voteTitle, string voteDescription, TimeSpan lastTime, string yesEmoji,
                                           string noEmoji, SocketGuild guild, IMessageChannel channel, SocketUser userWhoExecuted)
        {
            if (lastTime.TotalMilliseconds > Config.bot.VoteSettings.MaxVoteTime.TotalMilliseconds)
            {
                await channel.SendMessageAsync("The vote time succeeds the maximum allowed time for a vote to last!");

                return;
            }

            ServerList server = ServerListsManager.GetServer(guild);

            if (server.Votes.Count >= Config.bot.VoteSettings.MaxRunningVotesPerGuild)
            {
                await channel.SendMessageAsync(
                    $"There are already {Config.bot.VoteSettings.MaxRunningVotesPerGuild} votes running on this guild right now!\nEnd a vote to start a new one.");

                return;
            }

            //Setup Emojis
            Emoji yesEmote = new Emoji(yesEmoji);
            Emoji noEmote  = new Emoji(noEmoji);

            //Setup embed
            EmbedBuilder embed = new EmbedBuilder();

            embed.WithTitle("Setting up vote...");

            //Send the message and add the initial reactions
            IUserMessage voteMessage = await channel.SendMessageAsync("", false, embed.Build());

            await voteMessage.AddReactionAsync(yesEmote);

            await voteMessage.AddReactionAsync(noEmote);

            Vote newVote = new Vote
            {
                VoteMessageId        = voteMessage.Id,
                VoteMessageChannelId = channel.Id,
                VoteTitle            = voteTitle,
                VoteDescription      = voteDescription,
                VoteStarterUserId    = userWhoExecuted.Id,
                NoCount           = 0,
                YesCount          = 0,
                NoEmoji           = noEmoji,
                YesEmoji          = yesEmoji,
                VoteLastTime      = lastTime,
                VoteStartTime     = DateTime.Now,
                CancellationToken = new CancellationTokenSource()
            };

            //User last vote
            UserAccountsManager.GetAccount((SocketGuildUser)userWhoExecuted).UserLastVoteId = voteMessage.Id;
            UserAccountsManager.SaveAccounts();

            //Add our vote to the server list
            server.Votes.Add(newVote);
            ServerListsManager.SaveServerList();

            embed.WithTitle(voteTitle);
            embed.WithDescription(voteDescription +
                                  $"\nReact to this message with {yesEmoji} to say **YES** or react with {noEmoji} to say **NO**.");
            embed.WithFooter($"Vote started by {userWhoExecuted} at {DateTime.Now:g} and will end at {DateTime.Now.Add(lastTime):g}.", userWhoExecuted.GetAvatarUrl());

            await MessageUtils.ModifyMessage(voteMessage, embed);

            await RunVote(newVote, guild);
        }
Пример #5
0
        protected Dictionary <string, ImageInfo> GenerateContentIdsForImageUrlsFromHtmlContent()
        {
            var result = new Dictionary <string, ImageInfo>();

            // cid:{0}
            if (HtmlContent != null)
            {
                var originalMessageContent = HtmlContent; // TODO: save this somewhere
                // not sure if needed
                string html = string.Format("<html><head></head><body>{0}</body></html>", HtmlContent);

                List <Tuple <HtmlNode, string> > nodesToReplaceWithTextSmiley = new List <Tuple <HtmlNode, string> >();

                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(html);
                var imageNodes = doc.DocumentNode.SelectNodes("//img");
                if (imageNodes != null)
                {
                    foreach (var imageNode in imageNodes)
                    {
                        var imgUrl     = imageNode.GetAttributeValue("src", "");
                        var textSmiley = MessageUtils.GetTextReplacementForImageUrl(imgUrl);
                        if (!string.IsNullOrWhiteSpace(textSmiley))
                        {
                            nodesToReplaceWithTextSmiley.Add(Tuple.Create(imageNode, textSmiley));
                            continue;
                        }

                        if (string.IsNullOrWhiteSpace(imgUrl))
                        {
                            continue;
                        }

                        var cid = MimeUtils.GenerateMessageId();
                        imageNode.SetAttributeValue("src", $"cid:{cid}");

                        var imageInfo = new ImageInfo(imgUrl, imgUrl, ImageType.Public);

                        // Handles URLs like this: src =\"https://eu-api.asm.skype.com/v1/objects/0-weu-d11-00000000000000000000000000000000/views/imgo\"
                        var teamsImageUrlPattern = @"http.*?/objects/([0-9a-zA-Z-]+?)/views/imgo";
                        var match = Regex.Match(HtmlContent, teamsImageUrlPattern);
                        if (match.Success)
                        {
                            imageInfo.CacheKey  = match.Value;
                            imageInfo.ImageType = ImageType.TeamsWithAuthentication;
                        }

                        result.Add(cid, imageInfo);
                    }

                    foreach (var textReplacement in nodesToReplaceWithTextSmiley)
                    {
                        try
                        {
                            logger.Debug("Replacing image node with smiley {0} (HTML was: {1})", textReplacement.Item2, textReplacement.Item1.OuterHtml);
                            textReplacement.Item1.ParentNode.ReplaceChild(HtmlNode.CreateNode($"<span>{textReplacement.Item2}</span>"), textReplacement.Item1);
                        }
                        catch (Exception e)
                        {
                            logger.Error(e, "Exception while replacing image node with smiley");
                            continue;
                        }
                    }
                }
                var bodyElement = doc.DocumentNode.SelectSingleNode("//body");
                HtmlContent = bodyElement.InnerHtml;
            }
            return(result);
        }
Пример #6
0
        public async Task Ban(CommandContext ctx, [Description("The member to Ban.")] DiscordMember member, [Description("The reason on why to ban this member.")] string reason = "No reason given")
        {
            await member.BanAsync(7, reason : "Proty Ban : " + reason);

            await ctx.Channel.SendMessageAsync(MessageUtils.BuildSuccess($"Member {member.Mention} ({member.Id}) was banned from the server !"));
        }
        async void UpdateMessagesOnViewWillAppear()
        {
            await MessageUtils.RemoveAllOlderThan(Conf.MAX_MESSAGE_RETENTION_TIME_IN_MINUTES);

            InvokeOnMainThread(Update);
        }
Пример #8
0
        Widget _buildNotificationTitle()
        {
            var type     = this.notification.type;
            var data     = this.notification.data;
            var subTitle = new TextSpan();
            var content  = "";

            if (type == "project_liked")
            {
                subTitle = new TextSpan(
                    " 赞了你的文章",
                    style: CTextStyle.PLargeBody2
                    );
            }

            if (type == "project_message_commented")
            {
                if (data.parentComment.isNotEmpty())
                {
                    content  = $" “{MessageUtils.AnalyzeMessage(data.parentComment, this.mentions, false)}”";
                    subTitle = new TextSpan(
                        " 回复了你的评论" + content,
                        style: CTextStyle.PLargeBody2
                        );
                }
                else
                {
                    subTitle = new TextSpan(
                        " 评论了你的文章",
                        style: CTextStyle.PLargeBody2
                        );
                }
            }

            if (type == "project_participate_comment")
            {
                if (data.parentComment.isNotEmpty())
                {
                    content = $" “{MessageUtils.AnalyzeMessage(data.parentComment, this.mentions, false)}”";
                }

                subTitle = new TextSpan(
                    " 回复了你的评论" + content,
                    style: CTextStyle.PLargeBody2
                    );
            }

            if (type == "project_message_liked")
            {
                if (data.comment.isNotEmpty())
                {
                    content = $" “{MessageUtils.AnalyzeMessage(data.comment, this.mentions, false)}”";
                }

                subTitle = new TextSpan(
                    " 赞了你的评论" + content,
                    style: CTextStyle.PLargeBody2
                    );
            }

            if (type == "project_message_participate_liked")
            {
                if (data.comment.isNotEmpty())
                {
                    content = $" “{MessageUtils.AnalyzeMessage(data.comment, this.mentions, false)}”";
                }

                subTitle = new TextSpan(
                    " 赞了你的评论" + content,
                    style: CTextStyle.PLargeBody2
                    );
            }

            if (type == "followed")
            {
                subTitle = new TextSpan(
                    " 关注了你",
                    style: CTextStyle.PLargeBody2
                    );
            }

            if (type == "team_followed")
            {
                subTitle = new TextSpan(
                    children: new List <TextSpan> {
                    new TextSpan(" 关注了 "),
                    new TextSpan(data.teamName, recognizer: new TapGestureRecognizer {
                        onTap = () => { this.pushToTeamDetail(data.teamId); }
                    }, style: CTextStyle.PLargeBlue)
                },
                    style: CTextStyle.PLargeBody2
                    );
            }

            if (type == "project_article_publish")
            {
                string             name;
                GestureTapCallback onTap;
                if (this.notification.data.role == "team")
                {
                    name  = data.teamName;
                    onTap = () => this.pushToTeamDetail(obj: data.teamId);
                }
                else
                {
                    name  = data.fullname;
                    onTap = () => this.pushToUserDetail(obj: data.userId);
                }
                subTitle = new TextSpan(
                    children: new List <TextSpan> {
                    new TextSpan(text: name, recognizer: new TapGestureRecognizer {
                        onTap = onTap
                    }, style: CTextStyle.PLargeBlue),
                    new TextSpan(" 发布了新文章")
                },
                    style: CTextStyle.PLargeBody2
                    );
            }

            Widget projectTitle;

            if (data.projectTitle.isNotEmpty())
            {
                projectTitle = new Text(
                    data: data.projectTitle,
                    maxLines: 1,
                    style: CTextStyle.PLargeMedium,
                    overflow: TextOverflow.ellipsis
                    );
            }
            else
            {
                projectTitle = new Container();
            }

            List <TextSpan> textSpans = new List <TextSpan>();

            if (type != "project_article_publish")
            {
                textSpans.Add(new TextSpan(
                                  text: data.fullname,
                                  style: CTextStyle.PLargeMedium,
                                  recognizer: new TapGestureRecognizer {
                    onTap = () => this.pushToUserDetail(obj: data.userId)
                }
                                  ));
            }
            textSpans.Add(item: subTitle);

            return(new Column(
                       crossAxisAlignment: CrossAxisAlignment.start,
                       children: new List <Widget> {
                new RichText(
                    maxLines: 2,
                    text: new TextSpan(
                        children: textSpans
                        ),
                    overflow: TextOverflow.ellipsis
                    ),
                projectTitle
            }
                       ));
        }
Пример #9
0
        /// <summary>
        /// Highlight all word bookmark that not exist on data domain
        /// </summary>
        /// <param name="iBms"></param>
        public void ValidateBookmarkCollectionWithDomain(string key)
        {
            try
            {
                bool          isHighlight = false;
                List <string> unMatched   = new List <string>();

                //Get Bookmark Collection then put to WKL
                GetBookmarkCollection(key);

                ContentServiceProfile       contentProfile = Wkl.MainCtrl.ServiceCtrl.GetProfile(key).ContentService;
                Dictionary <string, string> wBm            = contentProfile.GetBookmarks_OListBM;

                //Get Internal Bookmark
                TemplateInfo templateInfo = Wkl.MainCtrl.CommonCtrl.GetTemplateInfo(
                    contentProfile.ValidateBookmark_ITemplateName);
                InternalBookmark interBm = templateInfo.InternalBookmark;

                //Get Domain Data
                foreach (string domainName in templateInfo.DomainNames)
                {
                    DomainInfo domainInfo = Wkl.MainCtrl.CommonCtrl.GetDomainInfo(domainName);
                    if (domainInfo != null)
                    {
                        InternalBookmarkDomain ibmDomain = interBm.GetInternalBookmarkDomain(domainName);
                        foreach (InternalBookmarkItem item in ibmDomain.InternalBookmarkItems)
                        {
                            if (!MarkupUtilities.IsExistOnDomain(item, domainInfo.Fields, true))
                            {
                                if (wBm.ContainsKey(item.Key) && wBm[item.Key] == item.BizName)
                                {
                                    contentProfile.HighlightBookmarkName = item.Key;
                                    unMatched.Add(item.BizName);
                                    HighlightBookmark(key);
                                    isHighlight = true;
                                }
                            }
                        }
                    }
                    else
                    {
                        isHighlight = true;
                    }
                }

                contentProfile.UnMatchedFields = unMatched;
                contentProfile.Result          = !isHighlight;
            }
            catch (BaseException srvExp)
            {
                Services.ServiceException newSrvExp = new Services.ServiceException(ErrorCode.ipe_ValidateWordBookmarkWithDomainError);
                newSrvExp.Errors.Add(srvExp);

                throw newSrvExp;
            }
            catch (Exception ex)
            {
                ServiceException srvExp = new ServiceException(ErrorCode.ipe_ValidateWordBookmarkWithDomainError,
                                                               MessageUtils.Expand(Properties.Resources.ipe_ValidateWordBookmarkWithDomainError, ex.Message), ex.StackTrace);

                throw srvExp;
            }
        }
        public IList <CCatalogFunctionNoAR> GetCatalogFunctionByUserId(string langid, string userid)
        {
            IList <CCatalogFunctionNoAR> result = new List <CCatalogFunctionNoAR>();

            ISession     ss   = holder.CreateSession(typeof(CCatalogFunctionNoARDaoOracleImp));
            ITransaction tran = ss.BeginTransaction();

            try
            {
                IList <MRoleUser> mroleuserlist = new List <MRoleUser>();
                //get role by userid
                SimpleQuery <MRoleUser> queryroleuser = new SimpleQuery <MRoleUser>(typeof(MRoleUser), @"
                                                from MRoleUser where Id.Userid=:userid");
                queryroleuser.SetParameter("userid", userid);

                mroleuserlist = queryroleuser.Execute();

                if (mroleuserlist.Count <= 0)
                {
                    throw new ApplicationException(MessageUtils.GetMessage("E0001"));
                }

                StringBuilder sb = new StringBuilder();
                //select f.catalogid,f.functionid,f.functionimage,f.functionindex,f.functionname,f.functionpath,f.langid,c.catalogimage,c.catalogname from (M_FUNCTION f inner join (select functionid from m_role_function
                //where roleid=1 group by functionid) r on (f.functionid=r.functionid)) left join
                //m_functioncatalog c on (f.catalogid=c.catalogid and f.langid=c.langid)
                //where f.langid='zh-CN'
                //order by f.catalogid,f.functionindex
                sb.Append(" select f.catalogid,");
                sb.Append(" f.functionid,");
                sb.Append(" f.functionimage,");
                sb.Append(" f.functionindex,");
                sb.Append(" f.functionname,");
                sb.Append(" f.functionpath,");
                sb.Append(" f.langid,");
                sb.Append(" c.catalogimage,");
                sb.Append(" c.catalogname ");
                sb.Append(" from (m_function f ");
                sb.Append(" inner join ");
                sb.Append(" (select functionid from m_role_function ");
                sb.Append(" where ");
                int cnt = 0;
                foreach (MRoleUser mroleuservo in mroleuserlist)
                {
                    if (cnt == 0)
                    {
                        sb.Append("roleid = :roleid" + cnt);
                    }
                    else
                    {
                        sb.Append("or roleid = :roleid" + cnt);
                    }
                    cnt++;
                }

                sb.Append(" group by functionid) r ");
                sb.Append(" on (f.functionid=r.functionid)) ");
                sb.Append(" left join");
                sb.Append(" m_functioncatalog c ");
                sb.Append(" on (f.catalogid=c.catalogid and f.langid=c.langid)");
                sb.Append(" where f.langid=:langid");
                sb.Append(" order by f.catalogid,f.functionindex");


                ISQLQuery querycatalogfunction = ss.CreateSQLQuery(sb.ToString());
                querycatalogfunction.AddScalar("langid", NHibernateUtil.String);
                querycatalogfunction.AddScalar("functionid", NHibernateUtil.Int32);
                querycatalogfunction.AddScalar("functionname", NHibernateUtil.String);
                querycatalogfunction.AddScalar("functionpath", NHibernateUtil.String);
                querycatalogfunction.AddScalar("catalogid", NHibernateUtil.Int32);
                querycatalogfunction.AddScalar("functionindex", NHibernateUtil.Int32);
                querycatalogfunction.AddScalar("functionimage", NHibernateUtil.String);
                querycatalogfunction.AddScalar("catalogimage", NHibernateUtil.String);
                querycatalogfunction.AddScalar("catalogname", NHibernateUtil.String);

                cnt = 0;
                foreach (MRoleUser mroleuservo in mroleuserlist)
                {
                    querycatalogfunction.SetParameter("roleid" + cnt, mroleuservo.Id.Roleid);
                    cnt++;
                }
                querycatalogfunction.SetParameter("langid", langid);

                result = querycatalogfunction.SetResultTransformer(Transformers.AliasToBean <CCatalogFunctionNoAR>()).List <CCatalogFunctionNoAR>();


                tran.Commit();
            }
            catch (Castle.ActiveRecord.Framework.ActiveRecordException ex)
            {
                tran.Rollback();
                throw new ApplicationException(ex.Message, ex);
            }
            catch (DbException ex)
            {
                tran.Rollback();
                throw new ApplicationException(ex.Message, ex);
            }
            finally
            {
                tran.Dispose();
                holder.ReleaseSession(ss);
            }

            return(result);
        }
Пример #11
0
        public override Widget build(BuildContext context)
        {
            string text;

            if (this.channel.lastMessage != null)
            {
                if (this.channel.lastMessage.deleted)
                {
                    text = "[此消息已被删除]";
                }
                else if (this.channel.lastMessage.type == ChannelMessageType.image)
                {
                    text = "[图片]";
                }
                else if (this.channel.lastMessage.type == ChannelMessageType.file)
                {
                    text = "[文件]";
                }
                else
                {
                    text = this.channel.lastMessage.content ?? "";
                }
            }
            else
            {
                text = "";
            }

            var contentTextSpans = new List <TextSpan>();

            if (this.channel.lastMessage.author?.fullName.isNotEmpty() ?? text.isNotEmpty() &&
                this.channel.lastMessage.author.id != this.myUserId)
            {
                contentTextSpans.Add(new TextSpan(
                                         $"{this.channel.lastMessage.author?.fullName}: ",
                                         style: CTextStyle.PRegularBody4
                                         ));
            }

            contentTextSpans.AddRange(MessageUtils.messageWithMarkdownToTextSpans(
                                          content: text,
                                          mentions: this.channel.lastMessage?.mentions,
                                          this.channel.lastMessage?.mentionEveryone ?? false,
                                          null,
                                          bodyStyle: CTextStyle.PRegularBody4,
                                          linkStyle: CTextStyle.PRegularBody4
                                          ));
            Widget message = new RichText(
                text: new TextSpan(
                    (this.channel.atMe || this.channel.atAll) && this.channel.unread > 0
                        ? "[有人@我] "
                        : "",
                    style: CTextStyle.PRegularError,
                    children: contentTextSpans
                    ),
                overflow: TextOverflow.ellipsis,
                maxLines: 1
                );

            // Don't show the time if nonce is 0, i.e. the time is not loaded yet.
            // Otherwise, the time would be like 0001/01/01 8:00
            string timeString = this.channel.lastMessage?.nonce != 0
                ? this.channel.lastMessage?.time.DateTimeString() ?? ""
                : "";

            Widget titleLine = new Container(
                padding: EdgeInsets.only(16),
                child: new Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: new List <Widget> {
                new Expanded(
                    child: new Text(
                        data: this.channel.name,
                        style: CTextStyle.PLargeMedium,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis
                        )
                    ),
                new Container(width: 16),
                new Text(
                    data: timeString,
                    style: CTextStyle.PSmallBody4
                    )
            }
                    )
                );

            return(new GestureDetector(
                       onTap: this.onTap,
                       child: new Container(
                           color: this.channel.isTop ? CColors.PrimaryBlue.withOpacity(0.04f) : CColors.White,
                           height: 72,
                           padding: EdgeInsets.symmetric(12, 16),
                           child: new Row(
                               children: new List <Widget> {
                new PlaceholderImage(
                    this.channel?.thumbnail ?? "",
                    48,
                    48,
                    4,
                    fit: BoxFit.cover,
                    true
                    ),
                new Expanded(
                    child: new Column(
                        children: new List <Widget> {
                    titleLine,
                    new Row(
                        children: new List <Widget> {
                        new Container(width: 16),
                        new Expanded(
                            child: message
                            ),
                        new NotificationDot(
                            this.channel.unread > 0
                                                        ? this.channel.mentioned > 0 ? $"{this.channel.mentioned}" : ""
                                                        : null,
                            margin: EdgeInsets.only(16)
                            )
                    }
                        )
                }
                        )
                    )
            }
                               )
                           )
                       ));
        }
Пример #12
0
        /// <summary>
        /// Plays a song in a given voice channel
        /// </summary>
        /// <param name="guild">The <see cref="SocketGuild"/> where we are playing in</param>
        /// <param name="channel">The <see cref="IMessageChannel"/> to log messages to</param>
        /// <param name="target">The target <see cref="IVoiceChannel"/> to play music in</param>
        /// <param name="user">The <see cref="IUser"/> who requested this command</param>
        /// <param name="search">The query to search for</param>
        /// <returns></returns>
        public async Task SendAudio(SocketGuild guild, IMessageChannel channel, IVoiceChannel target, IUser user,
                                    string search)
        {
            //Join the voice channel the user is in if we are already not in a voice channel
            if (!CheckIfServerIsPlayingMusic(guild, out ServerMusicItem serverMusicList))
            {
                await JoinAudio(guild, target, channel, user);

                serverMusicList = GetMusicList(guild.Id);
            }

            //Check to see if the user is in the playing audio channel
            if (!await CheckIfUserInChat(user, channel, serverMusicList))
            {
                return;
            }

            //Make sure the search isn't empty or null
            if (string.IsNullOrWhiteSpace(search))
            {
                await channel.SendMessageAsync("You need to input a search!");

                return;
            }

            IUserMessage message =
                await channel.SendMessageAsync($":musical_note: Preparing to play '{search}'");

            string songFileLocation;
            string songName;

            search.RemoveIllegalChars();

            try
            {
                songFileLocation = await GetOrDownloadSong(search, message, serverMusicList);

                //It failed
                if (songFileLocation == null)
                {
                    return;
                }

                Logger.Debug("Playing song from {@SongFileLocation}", songFileLocation);

                //This is so we say "Now playing 'Epic Song'" instead of "Now playing 'Epic Song.mp3'"
                songName = Path.GetFileName(songFileLocation)
                           .Replace($".{Config.bot.AudioSettings.MusicFileFormat.GetFormatExtension()}", "");

                //If there is already a song playing, cancel it
                await StopPlayingAudioOnServer(serverMusicList);
            }
            catch (Exception ex)
            {
                Logger.Error("An error occured while trying to get a song! {@Exception}", ex);
                return;
            }

            //Create music playback for our music format
            IMusicPlaybackInterface playbackInterface =
                serverMusicList.MusicPlayback = CreateMusicPlayback(songFileLocation);

            //Log (if enabled) to the console that we are playing a new song
            if (Config.bot.AudioSettings.LogPlayStopSongToConsole)
            {
                Logger.Info("The song {@SongName} on server {@GuildName}({@GuildId}) has started.", songName, guild.Name, guild.Id);
            }

            serverMusicList.CancellationSource = new CancellationTokenSource();
            CancellationToken token = serverMusicList.CancellationSource.Token;

            serverMusicList.IsPlaying = true;

            //Create an outgoing pcm stream
            await using AudioOutStream outStream = serverMusicList.AudioClient.CreatePCMStream(AudioApplication.Music);
            bool      fail       = false;
            bool      exit       = false;
            const int bufferSize = 1024;

            byte[] buffer = new byte[bufferSize];

            await MessageUtils.ModifyMessage(message, $":musical_note: Now playing **{songName}**.");

            while (!fail && !exit)
            {
                try
                {
                    if (token.IsCancellationRequested)
                    {
                        exit = true;
                        break;
                    }

                    //Read from stream
                    int read = await playbackInterface.ReadAudioStream(buffer, bufferSize, token);

                    if (read == 0)
                    {
                        exit = true;
                        break;
                    }

                    //Flush
                    await playbackInterface.Flush();

                    //Write it to outgoing pcm stream
                    await outStream.WriteAsync(buffer, 0, read, token);

                    //If we are still playing
                    if (serverMusicList.IsPlaying)
                    {
                        continue;
                    }

                    //For pausing the song
                    do
                    {
                        //Do nothing, wait till is playing is true
                        await Task.Delay(100, token);
                    } while (serverMusicList.IsPlaying == false);
                }
                catch (OperationCanceledException)
                {
                    //User canceled
                }
                catch (Exception ex)
                {
                    await channel.SendMessageAsync("Sorry, but an error occured while playing!");

                    if (Config.bot.ReportErrorsToOwner)
                    {
                        await Global.BotOwner.SendMessageAsync(
                            $"ERROR: {ex.Message}\nError occured while playing music on guild `{guild.Id}`.");
                    }

                    fail = true;
                }
            }

            if (Config.bot.AudioSettings.LogPlayStopSongToConsole)
            {
                Logger.Info("The song {@SongName} on server {@GuildName}({@GuildId}) has stopped.", songName, guild.Name, guild.Id);
            }

            //There wasn't a request to cancel
            if (!token.IsCancellationRequested)
            {
                await channel.SendMessageAsync($":musical_note: **{songName}** ended.");
            }

            //Clean up
            // ReSharper disable MethodSupportsCancellation
            await outStream.FlushAsync();

            outStream.Dispose();
            serverMusicList.IsPlaying = false;

            playbackInterface.EndAudioStream();
            serverMusicList.MusicPlayback = null;
            // ReSharper restore MethodSupportsCancellation

            serverMusicList.CancellationSource.Dispose();
            serverMusicList.CancellationSource = null;
        }
 public static void MarkAllMessagesAsRead()
 {
     MessageUtils.MarkAllAsRead();
     MessagingCenter.Send(Subscriber, MessagingCenterKeys.KEY_MESSAGE_STATUS_UPDATED);
 }
 public static async Task <List <MessageItemViewModel> > GetMessages()
 {
     return(MessageUtils.ToMessageItemViewModelList(await MessageUtils.GetMessages()));
 }
Пример #15
0
        private void webServerProc()
        {
            // 管理者権限がない場合は起動しない
            if (!WindowsUtils.IsExecuteAdminRole())
            {
                MessageUtils.showMessage(MessageBoxIcon.Warning, MessageResource.W0005);
                return;
            }

            listener = new HttpListener();
            listener.Prefixes.Add(prefix); // プレフィックスの登録
            try
            {
                listener.Start();
            }
            catch (HttpListenerException httpListenerException)
            {
                // すでにポートが使用中もしくは管理者権限なし
                LinearAudioPlayer.writeErrorMessage(httpListenerException);
                return;
            }

            while (true)
            {
                HttpListenerContext context = null;
                try
                {
                    context = listener.GetContext();
                }
                catch (HttpListenerException)
                {
                    // HTTP通信中に終了されたらどうしようもないので例外を握りつぶす
                }

                HttpListenerRequest  req = context.Request;
                HttpListenerResponse res = context.Response;

                Debug.WriteLine("request url: " + req.RawUrl);

                if (req.RawUrl.IndexOf("/LinearWebService") == -1)
                {
                    // WEBサーバ

                    string reqPath = req.RawUrl;
                    if (reqPath == "/")
                    {
                        reqPath = "ui/" + LinearGlobal.LinearConfig.ViewConfig.WebInterfaceTheme + ".html";
                    }

                    reqPath = reqPath.Replace("/", "\\");
                    reqPath = Regex.Replace(reqPath, "\\?.*", "");

                    // リクエストされたURLからファイルのパスを求める
                    string path = docRoot + reqPath;

                    // ファイルが存在すればレスポンス・ストリームに書き出す
                    if (File.Exists(path))
                    {
                        byte[] content = File.ReadAllBytes(path);
                        //string s = File.ReadAllText(path, Encoding.UTF8);
                        //byte[] content = Encoding.UTF8.GetBytes(s);
                        res.Headers[HttpResponseHeader.ContentType] = GuessContentType(Path.GetExtension(path));
                        res.OutputStream.Write(content, 0, content.Length);
                    }
                }
                else
                {
                    // RESTサービス
                    // TODO:変なもの受け取ったら落ちる

                    WebServiceResponseInfo response = new WebServiceResponseInfo();
                    var dict = req.QueryString;
                    var reqParamJsonString = JsonConvert.SerializeObject(
                        dict.AllKeys.ToDictionary(k => k, k => dict[k])
                        );

                    Debug.WriteLine("req data: " + reqParamJsonString);
                    WebServiceRequestInfo request =
                        JsonConvert.DeserializeObject <WebServiceRequestInfo>(reqParamJsonString);

                    response.action = request.action;
                    switch (request.action)
                    {
                    case "play":
                        Action playAction = () =>
                        {
                            LinearAudioPlayer.PlayController.play(LinearGlobal.CurrentPlayItemInfo.Id,
                                                                  false, false);
                        };
                        LinearGlobal.MainForm.BeginInvoke(playAction);
                        break;

                    case "pause":
                        Action pauseAction = () =>
                        {
                            LinearAudioPlayer.PlayController.pause();
                        };
                        LinearGlobal.MainForm.BeginInvoke(pauseAction);
                        break;

                    case "stop":
                        Action stopAction = () =>
                        {
                            LinearAudioPlayer.PlayController.stop();
                        };
                        LinearGlobal.MainForm.BeginInvoke(stopAction);
                        break;

                    case "previous":
                        Action previouspAction = () =>
                        {
                            LinearAudioPlayer.PlayController.previousPlay();
                        };
                        LinearGlobal.MainForm.BeginInvoke(previouspAction);
                        break;

                    case "forward":
                        Action forwardAction = () =>
                        {
                            if (LinearAudioPlayer.PlayController.isPlaying())
                            {
                                LinearAudioPlayer.PlayController.endOfStream();
                            }
                        };
                        LinearGlobal.MainForm.BeginInvoke(forwardAction);
                        break;

                    case "voldown":
                        Action volDownAction = () =>
                        {
                            int vol = LinearGlobal.Volume;
                            vol -= 5;
                            if (vol < 0)
                            {
                                vol = 0;
                            }
                            LinearGlobal.Volume = vol;
                            LinearGlobal.MainForm.ListForm.setVolume();
                        };
                        var voldownActionResult = LinearGlobal.MainForm.BeginInvoke(volDownAction);
                        voldownActionResult.AsyncWaitHandle.WaitOne();
                        response.volume = LinearGlobal.Volume;
                        break;

                    case "volup":
                        Action volUpAction = () =>
                        {
                            int vol = LinearGlobal.Volume;
                            vol += 5;
                            if (vol > 100)
                            {
                                vol = 100;
                            }
                            LinearGlobal.Volume = vol;
                            LinearGlobal.MainForm.ListForm.setVolume();
                        };
                        var volupActionResult = LinearGlobal.MainForm.BeginInvoke(volUpAction);
                        volupActionResult.AsyncWaitHandle.WaitOne();
                        response.volume = LinearGlobal.Volume;
                        break;

                    case "getplayinfo":
                        if (LinearAudioPlayer.PlayController != null)
                        {
                            response.playInfo  = LinearGlobal.CurrentPlayItemInfo;
                            response.isPlaying = LinearAudioPlayer.PlayController.isPlaying();
                            response.isPaused  = LinearAudioPlayer.PlayController.isPaused();
                            response.seekRatio = (int)(((float)LinearAudioPlayer.PlayController.getPosition() /
                                                        (float)LinearAudioPlayer.PlayController.getLength()) * 100);
                            if (response.seekRatio == 100)
                            {
                                response.seekRatio = 0;
                            }
                        }

                        break;

                    case "seek":
                        Action seekAction = () =>
                        {
                            double value = ((double)LinearAudioPlayer.PlayController.getLength()) *
                                           request.seekPosition;
                            LinearAudioPlayer.PlayController.setPosition((uint)value);
                        };
                        LinearGlobal.MainForm.ListForm.BeginInvoke(seekAction);
                        break;

                    case "getthemelist":
                        var themelist = new List <string>();
                        var filePaths = FileUtils.getFilePathList(
                            Application.StartupPath + LinearConst.WEB_DIRECTORY_NAME + "ui", SearchOption.TopDirectoryOnly);
                        foreach (string path in filePaths)
                        {
                            themelist.Add(Path.GetFileNameWithoutExtension(path));
                        }
                        response.themeList    = themelist.ToArray().Reverse().ToArray();
                        response.nowThemeName = LinearGlobal.LinearConfig.ViewConfig.WebInterfaceTheme;
                        break;

                    case "switchtheme":
                        LinearGlobal.LinearConfig.ViewConfig.WebInterfaceTheme = request.theme;
                        break;

                    case "getnowplaying":
                        response.nowPlaying = LinearAudioPlayer.PlayController.getNowPlayingList(10).Select(gi => new TrackInfo(gi.Id, gi.Title, gi.Artist, gi.Rating)).ToArray();
                        break;

                    case "addnowplaying":
                        response.nowPlaying = LinearAudioPlayer.PlayController.getNowPlayingList(request.skip, request.take).Select(gi => new TrackInfo(gi.Id, gi.Title, gi.Artist, gi.Rating)).ToArray();
                        break;

                    case "getanalyzeinfo":
                        var ai        = new AnalyzeInfo();
                        var startDate = SQLiteManager.Instance.executeQueryOnlyOne(SQLResource.SQL056);
                        if (startDate != null)
                        {
                            ai.StartDate         = startDate.ToString().Substring(0, 10);
                            ai.StartDateRelative = DateTimeUtils.getRelativeTimeString(startDate.ToString());
                        }
                        ai.TotalTracksCount         = (long)SQLiteManager.Instance.executeQueryOnlyOne(SQLResource.SQL057);
                        ai.TotalFavoriteTracksCount = (long)SQLiteManager.Instance.executeQueryOnlyOne(SQLResource.SQL058);
                        ai.TotalPlayCount           = (long)SQLiteManager.Instance.executeQueryOnlyOne(SQLResource.SQL059);
                        ai.TotalPalyHistoryCount    = (long)SQLiteManager.Instance.executeQueryOnlyOne(SQLResource.SQL060);
                        response.analyzeOverview    = ai;
                        break;

                    case "getrecentlist":
                        var paramList  = new List <DbParameter>();
                        var recentlist = new List <TrackInfo>();
                        var limit      = request.limit;
                        if (LinearGlobal.CurrentPlayItemInfo != null && request.offset == 0)
                        {
                            var ci = LinearGlobal.CurrentPlayItemInfo;
                            recentlist.Add(new TrackInfo(ci.Id, ci.Title, ci.Artist, "", "", ci.Rating));     // NowPlaying
                            limit--;
                        }
                        paramList.Add(new SQLiteParameter("Limit", limit));
                        paramList.Add(new SQLiteParameter("Offset", request.offset));
                        recentlist.AddRange(SQLiteManager.Instance.executeQueryNormal(SQLResource.SQL061, paramList).Select(o => new TrackInfo((long)o[0], o[1].ToString(), o[2].ToString(), o[3].ToString(), o[4].ToString(), int.Parse(o[5].ToString()))));
                        response.recentListen = recentlist.ToArray();

                        var offset = request.offset - limit < 0 ? 0 : request.offset - limit;
                        response.pagerPrevious = request.offset == 0 ? -1 : offset;
                        response.pagerNext     = response.recentListen.Length < limit ? -1 : request.offset + limit;
                        break;

                    case "gettopartist":
                        var sql       = SQLResource.SQL062;
                        var rangeType = (RangeType)Enum.Parse(typeof(RangeType), request.rangeType);
                        var where = "";
                        if (rangeType != RangeType.ALL)
                        {
                            where =
                                string.Format(
                                    "WHERE PH.PLAYDATETIME >= DATETIME(DATETIME('NOW','LOCALTIME'), '{0}','LOCALTIME')",
                                    _rangeDictionary[rangeType]);
                        }
                        else
                        {
                            sql = SQLResource.SQL064;
                        }
                        sql = sql.Replace(":Condition", where);
                        var topArtists = SQLiteManager.Instance.executeQueryNormal(sql, new SQLiteParameter("Limit", request.limit));
                        if (topArtists.Length > 0)
                        {
                            double maxcount = topArtists.Max(o => (long)o[1]);
                            response.topLists =
                                topArtists.Select(
                                    o =>
                                    new TrackInfo(o[0].ToString(), (long)o[1],
                                                  (int)((int.Parse(o[1].ToString()) / maxcount) * 100), o[2].ToString()))
                                .ToArray();
                        }
                        break;

                    case "gettoptrack":
                        var sql2       = SQLResource.SQL063;
                        var rangeType2 = (RangeType)Enum.Parse(typeof(RangeType), request.rangeType);
                        var where2     = "";
                        if (rangeType2 != RangeType.ALL)
                        {
                            where2 =
                                string.Format(
                                    "WHERE PH.PLAYDATETIME >= DATETIME(DATETIME('NOW','LOCALTIME'), '{0}','LOCALTIME')",
                                    _rangeDictionary[rangeType2]);
                        }
                        else
                        {
                            sql2 = SQLResource.SQL065;
                        }
                        sql2 = sql2.Replace(":Condition", where2);
                        var topTracks = SQLiteManager.Instance.executeQueryNormal(sql2, new SQLiteParameter("Limit", request.limit));
                        if (topTracks.Length > 0)
                        {
                            double maxcount2 = topTracks.Max(o => (long)o[2]);
                            response.topLists =
                                topTracks.Select(
                                    o =>
                                    new TrackInfo(o[0].ToString() + " - " + o[1].ToString(), (long)o[2],
                                                  (int)((int.Parse(o[2].ToString()) / maxcount2) * 100), o[3].ToString(),
                                                  int.Parse(o[4].ToString()))).ToArray();
                        }
                        break;

                    case "ratingon":
                    case "ratingoff":
                        if (request.id == -1)
                        {
                            break;
                        }
                        LinearEnum.RatingValue rating = request.action == "ratingon" ? LinearEnum.RatingValue.FAVORITE : LinearEnum.RatingValue.NORMAL;

                        Action setRatingAction = () =>
                        {
                            var rowIndex = LinearAudioPlayer.GridController.Find((int)GridController.EnuGrid.ID, request.id.ToString());
                            if (rowIndex != -1)
                            {
                                LinearAudioPlayer.GridController.setRatingIcon(rowIndex, rating);
                            }
                            if (request.id == LinearGlobal.CurrentPlayItemInfo.Id)
                            {
                                LinearGlobal.MainForm.setRating((int)rating);
                            }
                        };
                        LinearGlobal.MainForm.ListForm.BeginInvoke(setRatingAction);

                        SQLiteManager.Instance.executeNonQuery(
                            SQLBuilder.updateRating(
                                request.id, rating));
                        break;

                    case "skipnowplaying":
                        Action skipNowPlayingAction = () =>
                        {
                            LinearAudioPlayer.PlayController.skipPlayingList(request.id);
                            LinearAudioPlayer.PlayController.play(request.id, false, true);
                        };
                        LinearGlobal.MainForm.BeginInvoke(skipNowPlayingAction);

                        break;

                    case "getartwork":
                        if (LinearGlobal.CurrentPlayItemInfo.Artwork != null)
                        {
                            try
                            {
                                if (request.artworkSize == 0)
                                {
                                    request.artworkSize = 150;
                                }
                                Bitmap thumbnail = new Bitmap(request.artworkSize, request.artworkSize);
                                using (Graphics g = Graphics.FromImage(thumbnail))
                                {
                                    g.InterpolationMode =
                                        System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                                    g.DrawImage(LinearGlobal.CurrentPlayItemInfo.Artwork, 0, 0, request.artworkSize, request.artworkSize);
                                }
                                var artworkDirectoy = Application.StartupPath +
                                                      Path.Combine(Path.Combine(LinearConst.WEB_DIRECTORY_NAME, "img"), "artwork");
                                Directory.CreateDirectory(artworkDirectoy);
                                var artworkFileName = string.Format("{0}.png",
                                                                    LinearGlobal.CurrentPlayItemInfo.Id);
                                var artworkThumbFileName = string.Format("{0}-thumb.png",
                                                                         LinearGlobal.CurrentPlayItemInfo.Id);
                                LinearGlobal.CurrentPlayItemInfo.Artwork.Save(artworkDirectoy + "\\" + artworkFileName,
                                                                              System.Drawing.Imaging.ImageFormat.Png);
                                thumbnail.Save(artworkDirectoy + "\\" + artworkThumbFileName,
                                               System.Drawing.Imaging.ImageFormat.Png);
                                thumbnail.Dispose();
                                var oldfiles =
                                    Directory.GetFiles(artworkDirectoy, "*.png")
                                    .Where(a => Path.GetFileName(a).IndexOf(LinearGlobal.CurrentPlayItemInfo.Id.ToString()) == -1);
                                foreach (var file in oldfiles)
                                {
                                    File.Delete(file);
                                }
                                response.artworkUrl      = "../img/artwork/" + artworkFileName;
                                response.artworkThumbUrl = "../img/artwork/" + artworkThumbFileName;
                            }
                            catch (Exception)
                            {
                                response.artworkUrl = "";
                            }
                        }
                        else
                        {
                            response.artworkUrl = "";
                        }
                        break;
                    }


                    string resJsonString = JsonConvert.SerializeObject(response);
                    byte[] responseByte  = Encoding.UTF8.GetBytes(resJsonString);
                    res.OutputStream.Write(responseByte, 0, responseByte.Length);
                }
                res.Close();
            }
        }
Пример #16
0
        /// <summary>
        /// Add a bookmark into current document
        /// </summary>
        /// <param name="name">Name of bookmark</param>
        /// <param name="value">Value of bookmark</param>
        /// <param name="xsltType">XsltType (Select, Foreach or If)</param>
        /// <returns></returns>
        public bool AddBookmark(string key)
        {
            try
            {
                ServicesProfile      serviceProfile = Wkl.MainCtrl.ServiceCtrl.GetProfile(key);
                InternalBookmarkItem bm             = serviceProfile.ContentService.AddBookmark_IBookmark;
                Wkl.MainCtrl.CommonCtrl.CommonProfile.CurrentTemplateInfo.IsAdding = true;

                serviceProfile.ContentService.MarkProntDoc = true;
                switch (bm.Type)
                {
                case XsltType.Foreach:
                    AddDoubleBookmark(bm);
                    MarkProntoDoc(key);
                    break;

                case XsltType.If:
                    AddDoubleBookmark(bm);
                    MarkProntoDoc(key);
                    break;

                case XsltType.Select:
                    if (bm.IsImage())
                    {
                        serviceProfile.WbmKey          = bm.Key + ProntoMarkup.KeyImage;
                        serviceProfile.WbmValue        = MarkupUtilities.GenTextXslTag(bm.BizName, bm.Type, true);
                        serviceProfile.AlternativeText = MarkupUtilities.CreateAlternativeText(serviceProfile.WbmKey,
                                                                                               serviceProfile.WbmValue);
                        AddBookmarkImageEvent(key);
                    }
                    else
                    {
                        AddSingleBookmark(bm);
                    }
                    MarkProntoDoc(key);
                    break;

                case XsltType.Comment:
                    AddCommentBookmark(bm);
                    break;

                default:
                    break;
                }

                Wkl.MainCtrl.CommonCtrl.CommonProfile.CurrentTemplateInfo.IsAdding = false;
                return(true);
            }
            catch (BaseException srvExp)
            {
                Services.ServiceException newSrvExp = new Services.ServiceException(ErrorCode.ipe_AddBookmarkError);
                newSrvExp.Errors.Add(srvExp);

                throw newSrvExp;
            }
            catch (Exception ex)
            {
                ServiceException srvExp = new ServiceException(ErrorCode.ipe_AddBookmarkError,
                                                               MessageUtils.Expand(Properties.Resources.ipe_AddBookmarkError, ex.Message), ex.StackTrace);

                throw srvExp;
            }
        }
Пример #17
0
        private void WriteItems()
        {
            var freeItems = new List <Item>();

            if (_settings.LogicMode == LogicMode.Vanilla)
            {
                freeItems.Add(Item.FairyMagic);
                freeItems.Add(Item.MaskDeku);
                freeItems.Add(Item.SongHealing);
                freeItems.Add(Item.StartingSword);
                freeItems.Add(Item.StartingShield);
                freeItems.Add(Item.StartingHeartContainer1);
                freeItems.Add(Item.StartingHeartContainer2);

                if (_settings.ShortenCutscenes)
                {
                    //giants cs were removed
                    freeItems.Add(Item.SongOath);
                }

                WriteFreeItems(freeItems.ToArray());

                return;
            }

            //write free item (start item default = Deku Mask)
            freeItems.Add(_randomized.ItemList.Find(u => u.NewLocation == Item.MaskDeku).Item);
            freeItems.Add(_randomized.ItemList.Find(u => u.NewLocation == Item.SongHealing).Item);
            freeItems.Add(_randomized.ItemList.Find(u => u.NewLocation == Item.StartingSword).Item);
            freeItems.Add(_randomized.ItemList.Find(u => u.NewLocation == Item.StartingShield).Item);
            freeItems.Add(_randomized.ItemList.Find(u => u.NewLocation == Item.StartingHeartContainer1).Item);
            freeItems.Add(_randomized.ItemList.Find(u => u.NewLocation == Item.StartingHeartContainer2).Item);
            WriteFreeItems(freeItems.ToArray());

            //write everything else
            ItemSwapUtils.ReplaceGetItemTable(Values.ModsDirectory);
            ItemSwapUtils.InitItems();

            if (_settings.FixEponaSword)
            {
                ResourceUtils.ApplyHack(Values.ModsDirectory + "fix-epona");
            }
            if (_settings.PreventDowngrades)
            {
                ResourceUtils.ApplyHack(Values.ModsDirectory + "fix-downgrades");
            }
            if (_settings.AddCowMilk)
            {
                ResourceUtils.ApplyHack(Values.ModsDirectory + "fix-cow-bottle-check");
            }

            var newMessages = new List <MessageEntry>();

            foreach (var item in _randomized.ItemList)
            {
                // Unused item
                if (item.NewLocation == null)
                {
                    continue;
                }

                if (ItemUtils.IsBottleCatchContent(item.Item))
                {
                    ItemSwapUtils.WriteNewBottle(item.NewLocation.Value, item.Item);
                }
                else
                {
                    ChestTypeAttribute.ChestType?overrideChestType = null;
                    if ((item.Item.Name().Contains("Bombchu") || item.Item.Name().Contains("Shield")) && _randomized.Logic.Any(il => il.RequiredItemIds?.Contains(item.ID) == true || il.ConditionalItemIds?.Any(c => c.Contains(item.ID)) == true))
                    {
                        overrideChestType = ChestTypeAttribute.ChestType.LargeGold;
                    }
                    ItemSwapUtils.WriteNewItem(item.NewLocation.Value, item.Item, newMessages, _settings.UpdateShopAppearance, _settings.PreventDowngrades, _settings.UpdateChests && item.IsRandomized, overrideChestType, _settings.CustomStartingItemList.Contains(item.Item));
                }
            }

            var copyRupeesRegex = new Regex(": [0-9]+ Rupees");

            foreach (var newMessage in newMessages)
            {
                var oldMessage = _messageTable.GetMessage(newMessage.Id);
                if (oldMessage != null)
                {
                    var cost = copyRupeesRegex.Match(oldMessage.Message).Value;
                    newMessage.Message = copyRupeesRegex.Replace(newMessage.Message, cost);
                }
            }

            if (_settings.UpdateShopAppearance)
            {
                // update tingle shops
                foreach (var messageShopText in Enum.GetValues(typeof(MessageShopText)).Cast <MessageShopText>())
                {
                    var messageShop = messageShopText.GetAttribute <MessageShopAttribute>();
                    var item1       = _randomized.ItemList.First(io => io.NewLocation == messageShop.Items[0]).Item;
                    var item2       = _randomized.ItemList.First(io => io.NewLocation == messageShop.Items[1]).Item;
                    newMessages.Add(new MessageEntry
                    {
                        Id      = (ushort)messageShopText,
                        Header  = null,
                        Message = string.Format(messageShop.MessageFormat, item1.Name() + " ", messageShop.Prices[0], item2.Name() + " ", messageShop.Prices[1])
                    });
                }

                // update business scrub
                var businessScrubItem = _randomized.ItemList.First(io => io.NewLocation == Item.HeartPieceTerminaBusinessScrub).Item;
                newMessages.Add(new MessageEntry
                {
                    Id      = 0x1631,
                    Header  = null,
                    Message = $"\x1E\x3A\xD2Please! I'll sell you {MessageUtils.GetArticle(businessScrubItem)}\u0001{businessScrubItem.Name()}\u0000 if you just keep this place a secret...\x19\xBF".Wrap(35, "\u0011")
                });
                newMessages.Add(new MessageEntry
                {
                    Id      = 0x1632,
                    Header  = null,
                    Message = $"\u0006150 Rupees\u0000 for{MessageUtils.GetPronounOrAmount(businessScrubItem).ToLower()}!\u0011 \u0011\u0002\u00C2I'll buy {MessageUtils.GetPronoun(businessScrubItem)}\u0011No thanks\u00BF"
                });
                newMessages.Add(new MessageEntry
                {
                    Id      = 0x1634,
                    Header  = null,
                    Message = $"What about{MessageUtils.GetPronounOrAmount(businessScrubItem, "").ToLower()} for \u0006100 Rupees\u0000?\u0011 \u0011\u0002\u00C2I'll buy {MessageUtils.GetPronoun(businessScrubItem)}\u0011No thanks\u00BF"
                });

                // update biggest bomb bag purchase
                var biggestBombBagItem = _randomized.ItemList.First(io => io.NewLocation == Item.UpgradeBiggestBombBag).Item;
                newMessages.Add(new MessageEntry
                {
                    Id      = 0x15F5,
                    Header  = null,
                    Message = $"I sell {MessageUtils.GetArticle(biggestBombBagItem)}\u0001{MessageUtils.GetAlternateName(biggestBombBagItem)}\u0000, but I'm focusing my marketing efforts on \u0001Gorons\u0000.".Wrap(35, "\u0011").EndTextbox() + "What I'd really like to do is go back home and do business where I'm surrounded by trees and grass.\u0019\u00BF".Wrap(35, "\u0011")
                });
                newMessages.Add(new MessageEntry
                {
                    Id      = 0x15FF,
                    Header  = null,
                    Message = $"\x1E\x39\x8CRight now, I've got a \u0001special\u0011\u0000offer just for you.\u0019\u00BF"
                });
                newMessages.Add(new MessageEntry
                {
                    Id      = 0x1600,
                    Header  = null,
                    Message = $"\x1E\x38\x81I'll give you {MessageUtils.GetArticle(biggestBombBagItem, "my ")}\u0001{biggestBombBagItem.Name()}\u0000, regularly priced at \u00061000 Rupees\u0000...".Wrap(35, "\u0011").EndTextbox() + "In return, you'll give me just\u0011\u0006200 Rupees\u0000!\u0019\u00BF"
                });
                newMessages.Add(new MessageEntry
                {
                    Id      = 0x1606,
                    Header  = null,
                    Message = $"\x1E\x38\x81I'll give you {MessageUtils.GetArticle(biggestBombBagItem, "my ")}\u0001{biggestBombBagItem.Name()}\u0000, regularly priced at \u00061000 Rupees\u0000, for just \u0006200 Rupees\u0000!\u0019\u00BF".Wrap(35, "\u0011")
                });

                // update swamp scrub purchase
                var magicBeanItem = _randomized.ItemList.First(io => io.NewLocation == Item.ShopItemBusinessScrubMagicBean).Item;
                newMessages.Add(new MessageEntry
                {
                    Id      = 0x15E1,
                    Header  = null,
                    Message = $"\x1E\x39\xA7I'm selling {MessageUtils.GetArticle(magicBeanItem)}\u0001{MessageUtils.GetAlternateName(magicBeanItem)}\u0000 to Deku Scrubs, but I'd really like to leave my hometown.".Wrap(35, "\u0011").EndTextbox() + "I'm hoping to find some success in a livelier place!\u0019\u00BF".Wrap(35, "\u0011")
                });

                newMessages.Add(new MessageEntry
                {
                    Id      = 0x15E9,
                    Header  = null,
                    Message = $"\x1E\x3A\u00D2Do you know what {MessageUtils.GetArticle(magicBeanItem)}\u0001{MessageUtils.GetAlternateName(magicBeanItem)}\u0000 {MessageUtils.GetVerb(magicBeanItem)}, sir?".Wrap(35, "\u0011") + $"\u0011I'll sell you{MessageUtils.GetPronounOrAmount(magicBeanItem).ToLower()} for \u000610 Rupees\u0000.\u0019\u00BF"
                });

                // update ocean scrub purchase
                var greenPotionItem = _randomized.ItemList.First(io => io.NewLocation == Item.ShopItemBusinessScrubGreenPotion).Item;
                newMessages.Add(new MessageEntry
                {
                    Id      = 0x1608,
                    Header  = null,
                    Message = $"\x1E\x39\xA7I'm selling {MessageUtils.GetArticle(greenPotionItem)}\u0001{MessageUtils.GetAlternateName(greenPotionItem)}\u0000, but I'm focusing my marketing efforts on Zoras.".Wrap(35, "\u0011").EndTextbox() + "Actually, I'd like to do business someplace where it's cooler and the air is clean.\u0019\u00BF".Wrap(35, "\u0011")
                });

                newMessages.Add(new MessageEntry
                {
                    Id      = 0x1612,
                    Header  = null,
                    Message = $"\x1E\x39\x8CI'll sell you {MessageUtils.GetArticle(greenPotionItem)}\u0001{greenPotionItem.Name()}\u0000 for \u000640 Rupees\u0000!\u00E0\u00BF".Wrap(35, "\u0011")
                });

                // update canyon scrub purchase
                var bluePotionItem = _randomized.ItemList.First(io => io.NewLocation == Item.ShopItemBusinessScrubBluePotion).Item;
                newMessages.Add(new MessageEntry
                {
                    Id      = 0x161C,
                    Header  = null,
                    Message = $"\x1E\x39\xA7I'm here to sell {MessageUtils.GetArticle(bluePotionItem)}\u0001{MessageUtils.GetAlternateName(bluePotionItem)}\u0000.".Wrap(35, "\u0011").EndTextbox() + "Actually, I want to do business in the sea breeze while listening to the sound of the waves.\u0019\u00BF".Wrap(35, "\u0011")
                });

                newMessages.Add(new MessageEntry
                {
                    Id      = 0x1626,
                    Header  = null,
                    Message = $"\x1E\x3A\u00D2Don't you need {MessageUtils.GetArticle(bluePotionItem)}\u0001{MessageUtils.GetAlternateName(bluePotionItem)}\u0000? I'll sell you{MessageUtils.GetPronounOrAmount(bluePotionItem).ToLower()} for \u0006100 Rupees\u0000.\u0019\u00BF".Wrap(35, "\u0011")
                });

                newMessages.Add(new MessageEntry
                {
                    Id      = 0x15EA,
                    Header  = null,
                    Message = $"Do we have a deal?\u0011 \u0011\u0002\u00C2Yes\u0011No\u00BF"
                });

                // update gorman bros milk purchase
                var gormanBrosMilkItem = _randomized.ItemList.First(io => io.NewLocation == Item.ShopItemGormanBrosMilk).Item;
                newMessages.Add(new MessageEntry
                {
                    Id      = 0x3463,
                    Header  = null,
                    Message = $"Won'tcha buy {MessageUtils.GetArticle(gormanBrosMilkItem)}\u0001{MessageUtils.GetAlternateName(gormanBrosMilkItem)}\u0000?\u0019\u00BF".Wrap(35, "\u0011")
                });
                newMessages.Add(new MessageEntry
                {
                    Id      = 0x3466,
                    Header  = null,
                    Message = $"\u000650 Rupees\u0000 will do ya for{MessageUtils.GetPronounOrAmount(gormanBrosMilkItem).ToLower()}.\u0011 \u0011\u0002\u00C2I'll buy {MessageUtils.GetPronoun(gormanBrosMilkItem)}\u0011No thanks\u00BF"
                });
                newMessages.Add(new MessageEntry
                {
                    Id      = 0x346B,
                    Header  = null,
                    Message = $"Buyin' {MessageUtils.GetArticle(gormanBrosMilkItem)}\u0001{MessageUtils.GetAlternateName(gormanBrosMilkItem)}\u0000?\u0019\u00BF".Wrap(35, "\u0011")
                });
                newMessages.Add(new MessageEntry
                {
                    Id      = 0x348F,
                    Header  = null,
                    Message = $"Seems like we're the only ones who have {MessageUtils.GetArticle(gormanBrosMilkItem)}\u0001{MessageUtils.GetAlternateName(gormanBrosMilkItem)}\u0000. Hyuh, hyuh. If you like, I'll sell you{MessageUtils.GetPronounOrAmount(gormanBrosMilkItem).ToLower()}.\u0019\u00BF".Wrap(35, "\u0011")
                });
                newMessages.Add(new MessageEntry
                {
                    Id      = 0x3490,
                    Header  = null,
                    Message = $"\u000650 Rupees\u0000 will do you for{MessageUtils.GetPronounOrAmount(gormanBrosMilkItem).ToLower()}!\u0011 \u0011\u0002\u00C2I'll buy {MessageUtils.GetPronoun(gormanBrosMilkItem)}\u0011No thanks\u00BF"
                });

                // update lottery message
                var lotteryItem = _randomized.ItemList.First(io => io.NewLocation == Item.MundaneItemLotteryPurpleRupee).Item;
                newMessages.Add(new MessageEntry
                {
                    Id      = 0x2B5C,
                    Header  = null,
                    Message = $"Would you like the chance to buy your dreams for \u000610 Rupees\u0000?".Wrap(35, "\u0011").EndTextbox() + $"Pick any three numbers, and if those are picked, you'll win {MessageUtils.GetArticle(lotteryItem)}\u0001{lotteryItem.Name()}\u0000. It's only for the \u0001first\u0000 person!\u0019\u00BF".Wrap(35, "\u0011")
                });
            }

            // replace "Razor Sword is now blunt" message with get-item message for Kokiri Sword.
            newMessages.Add(new MessageEntry
            {
                Id     = 0xF9,
                Header = new byte[11] {
                    0x06, 0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
                },
                Message = $"You got the \x01Kokiri Sword\x00!\u0011This is a hidden treasure of\u0011the Kokiri, but you can borrow it\u0011for a while.\u00BF",
            });

            // replace Magic Power message
            newMessages.Add(new MessageEntry
            {
                Id      = 0xC8,
                Header  = null,
                Message = $"\u0017You've been granted \u0002Magic Power\u0000!\u0018\u0011Replenish it with \u0001Magic Jars\u0000\u0011and \u0001Potions\u0000.\u00BF",
            });

            // update Bank Reward messages
            newMessages.Add(new MessageEntry
            {
                Id      = 0x45C,
                Header  = null,
                Message = "\u0017What's this? You've already saved\u0011up \u0001500 Rupees\u0000!?!\u0018\u0011\u0013\u0012Well, little guy, here's your special\u0011gift. Take it!\u00E0\u00BF",
            });
            newMessages.Add(new MessageEntry
            {
                Id      = 0x45D,
                Header  = null,
                Message = "\u0017What's this? You've already saved\u0011up \u00011000 Rupees\u0000?!\u0018\u0011\u0013\u0012Well, little guy, I can't take any\u0011more deposits. Sorry, but this is\u0011all I can give you.\u00E0\u00BF",
            });

            if (_settings.AddSkulltulaTokens)
            {
                ResourceUtils.ApplyHack(Values.ModsDirectory + "fix-skulltula-tokens");

                newMessages.Add(new MessageEntry
                {
                    Id     = 0x51,
                    Header = new byte[11] {
                        0x02, 0x00, 0x52, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
                    },
                    Message = $"\u0017You got an \u0005Ocean Gold Skulltula\u0011Spirit\0!\u0018\u001F\u0000\u0010 This is your \u0001\u000D\u0000 one!\u00BF",
                });
                newMessages.Add(new MessageEntry
                {
                    Id     = 0x52,
                    Header = new byte[11] {
                        0x02, 0x00, 0x52, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
                    },
                    Message = $"\u0017You got a \u0006Swamp Gold Skulltula\u0011Spirit\0!\u0018\u001F\u0000\u0010 This is your \u0001\u000D\u0000 one!\u00BF",
                });
            }

            if (_settings.AddStrayFairies)
            {
                ResourceUtils.ApplyHack(Values.ModsDirectory + "fix-fairies");
            }

            var dungeonItemMessageIds = new byte[] {
                0x3C, 0x3D, 0x3E, 0x3F, 0x74,
                0x40, 0x4D, 0x4E, 0x53, 0x75,
                0x54, 0x61, 0x64, 0x6E, 0x76,
                0x70, 0x71, 0x72, 0x73, 0x77,
            };

            var dungeonNames = new string[]
            {
                "\u0006Woodfall Temple\u0000",
                "\u0002Snowhead Temple\u0000",
                "\u0005Great Bay Temple\u0000",
                "\u0004Stone Tower Temple\u0000"
            };

            var dungeonItemMessages = new string[]
            {
                "\u0017You found a \u0001Small Key\u0000 for\u0011{0}!\u0018\u00BF",
                "\u0017You found the \u0001Boss Key\u0000 for\u0011{0}!\u0018\u00BF",
                "\u0017You found the \u0001Dungeon Map\u0000 for\u0011{0}!\u0018\u00BF",
                "\u0017You found the \u0001Compass\u0000 for\u0011{0}!\u0018\u00BF",
                "\u0017You found a \u0001Stray Fairy\u0000 from\u0011{0}!\u0018\u001F\u0000\u0010\u0011This is your \u0001\u000C\u0000 one!\u00BF",
            };

            var dungeonItemIcons = new byte[]
            {
                0x3C, 0x3D, 0x3E, 0x3F, 0xFE
            };

            for (var i = 0; i < dungeonItemMessageIds.Length; i++)
            {
                var messageId   = dungeonItemMessageIds[i];
                var icon        = dungeonItemIcons[i % 5];
                var dungeonName = dungeonNames[i / 5];
                var message     = string.Format(dungeonItemMessages[i % 5], dungeonName);

                newMessages.Add(new MessageEntry
                {
                    Id     = messageId,
                    Header = new byte[11] {
                        0x02, 0x00, icon, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
                    },
                    Message = message
                });
            }

            _messageTable.UpdateMessages(newMessages);

            if (_settings.AddShopItems)
            {
                ResourceUtils.ApplyHack(Values.ModsDirectory + "fix-shop-checks");
            }
        }
Пример #18
0
        /// <summary>
        /// Get bookmark collection in word
        /// </summary>
        /// <returns>Dictionary with key is bookmark name and value is bookmark text</returns>
        public void GetDistinctBookmarks(string key)
        {
            //1.Get All Bookmarks
            //2.Do not add EndIf, EndForEach bookmark
            //3.If a bookmark is existed in List, increase number entry
            //4.Else insert to list.
            try
            {
                ContentServiceProfile contentProfile = Wkl.MainCtrl.ServiceCtrl.GetProfile(key).ContentService;
                List <BookmarkItem>   listBookmarks  = new List <BookmarkItem>();
                Bookmarks             bms            = Wkl.MainCtrl.CommonCtrl.CommonProfile.Bookmarks;

                for (int j = 1; j <= bms.Count; j++)
                {
                    Bookmark bookmark = bms[j];

                    //2.Do not add EndIf, EndForEach bookmark
                    if (!MarkupUtilities.GetRangeText(bookmark.Range).Contains(Constants.BookMarkControl.EndIfTag))
                    {
                        BookmarkItem item = new BookmarkItem(bookmark.Name, string.Empty, string.Empty, bookmark);
                        if (bookmark.Name.Contains("Image"))
                        {
                            GetInternalBookmark(key);
                            InternalBookmark internalBM = Wkl.MainCtrl.ServiceCtrl.GetProfile(key).Ibm;
                            foreach (InternalBookmarkDomain ibmDomain in internalBM.InternalBookmarkDomains)
                            {
                                foreach (InternalBookmarkItem internalItem in ibmDomain.InternalBookmarkItems)
                                {
                                    if (internalItem.Key.CompareTo(bookmark.Name) == 0)
                                    {
                                        item.Value       = internalItem.BizName;
                                        item.DisplayName = SplitValue(internalItem.BizName);
                                    }
                                }
                            }
                        }
                        else
                        {
                            item.Value       = MarkupUtilities.GetRangeText(bookmark.Range);
                            item.DisplayName = SplitValue(item.Value);
                        }

                        if (listBookmarks.Count == 0)
                        {
                            listBookmarks.Add(item);
                        }
                        else
                        {
                            int  n       = -1;
                            bool existed = false;
                            for (int i = 0; i < listBookmarks.Count; i++)
                            {
                                n += 1;
                                if (listBookmarks[i].Value.Equals(item.Value))
                                {
                                    existed = true;
                                    break;
                                }
                            }

                            //3.
                            if (existed)
                            {
                                listBookmarks[n].NumberEntry += 1;
                                listBookmarks[n].Items.Add(bookmark);
                            }
                            else//4.
                            {
                                listBookmarks.Add(item);
                            }
                        }
                    }
                }
                contentProfile.GetDistinctBM_OListBM = listBookmarks;
            }
            catch (BaseException srvExp)
            {
                Services.ServiceException newSrvExp = new Services.ServiceException(ErrorCode.ipe_GetDistinctBookmarkError);
                newSrvExp.Errors.Add(srvExp);

                throw newSrvExp;
            }
            catch (Exception ex)
            {
                ServiceException srvExp = new ServiceException(ErrorCode.ipe_GetDistinctBookmarkError,
                                                               MessageUtils.Expand(Properties.Resources.ipe_GetDistinctBookmarkError, ex.Message), ex.StackTrace);

                throw srvExp;
            }
        }
Пример #19
0
        public async Task Kick(CommandContext ctx, [Description("The member to Kick.")] DiscordMember member, [Description("The reason on why to kick this member.")] string reason = "No reason given")
        {
            await member.RemoveAsync("Proty Kick : " + reason);

            await ctx.Channel.SendMessageAsync(MessageUtils.BuildSuccess($"Member {member.Mention} ({member.Id}) was kicked from the server !"));
        }
        private async void Init()
        {
            MessagesViewModel.SubscribeMessages(this, ClearAndAddNewMessages);

            _messagesList        = FindViewById <ListView>(Resource.Id.messages_list);
            _noItemsTextView     = FindViewById <TextView>(Resource.Id.no_items_description);
            _lastUpdatedTextView = FindViewById <TextView>(Resource.Id.last_updated);

            _messagesList.Divider       = null;
            _messagesList.DividerHeight = 0;


            TextView title = FindViewById <TextView>(Resource.Id.messages_page_title);

            title.Text = MessagesViewModel.MESSAGES_HEADER;
            title.SetAccessibilityDelegate(AccessibilityUtils.GetHeadingAccessibilityDelegate());

            string headerText     = MessagesViewModel.MESSAGES_NO_ITEMS_TITLE;
            int    unreadMessages = (await MessageUtils.GetAllUnreadMessages()).Count;
            int    messages       = (await MessageUtils.GetMessages()).Count;

            if (unreadMessages > 0)
            {
                headerText = MessagesViewModel.MESSAGES_NEW_MESSAGES_HEADER;
            }
            else if (messages > 0)
            {
                headerText = MessagesViewModel.MESSAGES_NO_NEW_MESSAGES_HEADER;
            }

            TextView subheader = FindViewById <TextView>(Resource.Id.messages_page_sub_header);

            subheader.Text = headerText;
            subheader.SetAccessibilityDelegate(AccessibilityUtils.GetHeadingAccessibilityDelegate());

            string lastUpdatedString = MessagesViewModel.LastUpdateString;

            if (lastUpdatedString == "")
            {
                _lastUpdatedTextView.Visibility = ViewStates.Gone;
            }
            else
            {
                _lastUpdatedTextView.Visibility = ViewStates.Visible;
                _lastUpdatedTextView.Text       = MessagesViewModel.LastUpdateString;
            }

            _noItemsTextView.Text = MessagesViewModel.MESSAGES_NO_ITEMS_DESCRIPTION;

            _closeButton        = FindViewById <ImageView>(Resource.Id.arrow_back);
            _closeButton.Click += new StressUtils.SingleClick(OnCloseBtnClicked).Run;
            _closeButton.ContentDescription = MessagesViewModel.MESSAGES_ACCESSIBILITY_CLOSE_BUTTON;

            _adapterMessages                  = new MessagesAdapter(this, new MessageItemViewModel[0]);
            _messagesList.Adapter             = _adapterMessages;
            _messagesList.OnItemClickListener = new ItemClickListener(_adapterMessages);
            ShowList(false);

            View rootView = Window.DecorView.RootView;

            rootView.LayoutDirection = LayoutUtils.GetLayoutDirection();

            _closeButton.SetBackgroundResource(LayoutUtils.GetBackArrow());
        }
Пример #21
0
 public static string AlternateName(this ItemObject itemObject)
 {
     return(MessageUtils.GetAlternateName(itemObject.DisplayName()));
 }
Пример #22
0
        /// <inheritdoc />
        public virtual async Task IssueCredentialAsync(Pool pool, Wallet wallet, string issuerDid, string credentialId,
                                                       Dictionary <string, string> values)
        {
            var credentialRecord = await RecordService.GetAsync <CredentialRecord>(wallet, credentialId);

            if (values != null && values.Count > 0)
            {
                credentialRecord.ValuesJson = CredentialUtils.FormatCredentialValues(values);
            }

            var definitionRecord =
                await SchemaService.GetCredentialDefinitionAsync(wallet, credentialRecord.CredentialDefinitionId);

            var connection = await ConnectionService.GetAsync(wallet, credentialRecord.ConnectionId);

            if (credentialRecord.State != CredentialState.Requested)
            {
                throw new Exception(
                          $"Credential sate was invalid. Expected '{CredentialState.Requested}', found '{credentialRecord.State}'");
            }

            string            revocationRegistryId = null;
            BlobStorageReader tailsReader          = null;

            if (definitionRecord.SupportsRevocation)
            {
                var revocationRecordSearch = await RecordService.SearchAsync <RevocationRegistryRecord>(
                    wallet, new SearchRecordQuery { { TagConstants.CredentialDefinitionId, definitionRecord.DefinitionId } }, null, 1);

                var revocationRecord = revocationRecordSearch.First();

                revocationRegistryId = revocationRecord.RevocationRegistryId;
                tailsReader          = await TailsService.OpenTailsAsync(revocationRecord.TailsFile);
            }

            var issuedCredential = await AnonCreds.IssuerCreateCredentialAsync(wallet, credentialRecord.OfferJson,
                                                                               credentialRecord.RequestJson, credentialRecord.ValuesJson, revocationRegistryId, tailsReader);

            if (definitionRecord.SupportsRevocation)
            {
                await LedgerService.SendRevocationRegistryEntryAsync(wallet, pool, issuerDid,
                                                                     revocationRegistryId,
                                                                     "CL_ACCUM", issuedCredential.RevocRegDeltaJson);

                credentialRecord.CredentialRevocationId = issuedCredential.RevocId;
            }

            var credentialDetails = new CredentialDetails
            {
                CredentialJson       = issuedCredential.CredentialJson,
                RevocationRegistryId = revocationRegistryId
            };

            await credentialRecord.TriggerAsync(CredentialTrigger.Issue);

            await RecordService.UpdateAsync(wallet, credentialRecord);

            var credential = await MessageSerializer.PackSealedAsync <CredentialMessage>(credentialDetails, wallet,
                                                                                         connection.MyVk,
                                                                                         connection.TheirVk);

            credential.Type = MessageUtils.FormatDidMessageType(connection.TheirDid, MessageTypes.Credential);

            await RouterService.ForwardAsync(new ForwardEnvelopeMessage
            {
                Content = credential.ToJson(),
                Type    = MessageUtils.FormatDidMessageType(connection.TheirDid, MessageTypes.Forward)
            }, connection.Endpoint);
        }
Пример #23
0
        IEnumerable <Widget> _buildComments(BuildContext context)
        {
            List <string> channelComments = new List <string>();

            if (this.widget.viewModel.channelMessageList.ContainsKey(key: this._article.channelId))
            {
                channelComments = this.widget.viewModel.channelMessageList[key : this._article.channelId];
            }

            var mediaQuery = MediaQuery.of(context);
            var comments   = new List <Widget> {
                new Container(
                    color: CColors.White,
                    width: mediaQuery.size.width,
                    padding: EdgeInsets.only(16, 16, 16),
                    child: new Text(
                        "评论",
                        style: CTextStyle.H5,
                        textAlign: TextAlign.left
                        )
                    )
            };

            var titleHeight = CTextUtils.CalculateTextHeight(
                "评论",
                CTextStyle.H5,
                mediaQuery.size.width - 16 * 2 // 16 is horizontal padding
                ) + 16;                        // 16 is top padding

            float safeAreaPadding = 0;

            if (Application.platform != RuntimePlatform.Android)
            {
                safeAreaPadding = mediaQuery.padding.vertical;
            }

            var height = mediaQuery.size.height - navBarHeight - 44 - safeAreaPadding;

            if (channelComments.Count == 0)
            {
                var blankView = new Container(
                    height: height - titleHeight,
                    child: new BlankView(
                        "快来写下第一条评论吧",
                        "image/default-comment"
                        )
                    );
                comments.Add(item: blankView);
                return(comments);
            }

            var   messageDict    = this.widget.viewModel.channelMessageDict[key : this._article.channelId];
            float contentHeights = 0;

            foreach (var commentId in channelComments)
            {
                if (!messageDict.ContainsKey(key: commentId))
                {
                    break;
                }

                var message     = messageDict[key : commentId];
                var userLicense = CCommonUtils.GetUserLicense(userId: message.author.id,
                                                              userLicenseMap: this.widget.viewModel.userLicenseDict);
                bool isPraised      = _isPraised(message: message, loginUserId: this.widget.viewModel.loginUserId);
                var  parentName     = "";
                var  parentAuthorId = "";
                if (message.upperMessageId.isNotEmpty())
                {
                    if (messageDict.ContainsKey(key: message.upperMessageId))
                    {
                        var parentMessage = messageDict[key : message.upperMessageId];
                        parentName     = parentMessage.author.fullName;
                        parentAuthorId = parentMessage.author.id;
                    }
                }
                else if (message.parentMessageId.isNotEmpty())
                {
                    if (messageDict.ContainsKey(key: message.parentMessageId))
                    {
                        var parentMessage = messageDict[key : message.parentMessageId];
                        parentName     = parentMessage.author.fullName;
                        parentAuthorId = parentMessage.author.id;
                    }
                }

                var content = MessageUtils.AnalyzeMessage(message.content, message.mentions,
                                                          message.mentionEveryone) + (parentName.isEmpty() ? "" : $"回复@{parentName}");
                var contentHeight = CTextUtils.CalculateTextHeight(
                    content,
                    CTextStyle.PLargeBody,
                    // 16 is horizontal padding, 24 is avatar size, 8 is content left margin to avatar
                    mediaQuery.size.width - 16 * 2 - 24 - 8
                    ) + 16 + 24 + 3 + 5 + 22 + 12;
                // 16 is top padding, 24 is avatar size, 3 is content top margin to avatar, 5 is content bottom margin to commentTime
                // 22 is commentTime height, 12 is commentTime bottom margin
                contentHeights += contentHeight;
                var card = new CommentCard(
                    message: message,
                    userLicense: userLicense,
                    isPraised: isPraised,
                    parentName: parentName,
                    parentAuthorId: parentAuthorId,
                    () => ReportManager.showReportView(
                        isLoggedIn: this.widget.viewModel.isLoggedIn,
                        reportType: ReportType.comment,
                        () => this.widget.actionModel.pushToLogin(),
                        () => this.widget.actionModel.pushToReport(arg1: commentId, arg2: ReportType.comment)
                        ),
                    replyCallBack: () => this._sendComment(
                        "Article_Comment",
                        message.parentMessageId.isNotEmpty() ? message.parentMessageId : commentId,
                        message.parentMessageId.isNotEmpty() ? commentId : "",
                        message.author.fullName.isEmpty() ? "" : message.author.fullName
                        ),
                    praiseCallBack: () => {
                    if (!this.widget.viewModel.isLoggedIn)
                    {
                        this.widget.actionModel.pushToLogin();
                    }
                    else
                    {
                        if (isPraised)
                        {
                            this.widget.actionModel.removeLikeComment(arg: message);
                        }
                        else
                        {
                            this.widget.actionModel.likeComment(arg: message);
                        }
                    }
                },
                    pushToUserDetail: this.widget.actionModel.pushToUserDetail
                    );
                comments.Add(item: card);
            }

            float endHeight = 0;

            if (!this._article.hasMore)
            {
                comments.Add(new EndView());
                endHeight = 52;
            }

            if (titleHeight + contentHeights + endHeight < height)
            {
                return(new List <Widget> {
                    new Container(
                        height: height,
                        child: new Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: comments
                            )
                        )
                });
            }

            return(comments);
        }
Пример #24
0
        /// <summary>
        /// Receive and process message
        /// </summary>
        protected virtual void OnReceiveMessage(object client)
        {
            using (TcpClient tcpClient = client as TcpClient)
            {
                this.m_traceSource.TraceEvent(EventLevel.Verbose, "Accepted connection on {0} from {1}", this.m_listener.LocalEndpoint, tcpClient.Client.RemoteEndPoint);
                NetworkStream stream = tcpClient.GetStream();
                try
                {
                    // Now read to a string
                    DateTime lastReceive = DateTime.Now;

                    while (DateTime.Now.Subtract(lastReceive) < this.m_timeout)
                    {
                        if (!stream.DataAvailable)
                        {
                            Thread.Sleep(10);
                            continue;
                        }

                        // Read LLP head byte
                        int llpByte = stream.ReadByte();
                        if (llpByte != START_TX) // first byte must be HT
                        {
                            throw new InvalidOperationException("Invalid LLP First Byte");
                        }

                        // Standard stream stuff, read until the stream is exhausted
                        StringBuilder messageData = new StringBuilder();
                        byte[]        buffer = new byte[1024];
                        bool          receivedEOF = false, scanForCr = false;

                        while (!receivedEOF)
                        {
                            if (DateTime.Now.Subtract(lastReceive) > this.m_timeout)
                            {
                                throw new TimeoutException("Data not received in the specified amount of time. Increase the timeout or check the network connection");
                            }

                            if (!stream.DataAvailable)
                            {
                                Thread.Sleep(10);
                                continue;
                            }

                            int br = stream.Read(buffer, 0, 1024);
                            messageData.Append(System.Text.Encoding.UTF8.GetString(buffer, 0, br));

                            // Need to check for CR?
                            if (scanForCr)
                            {
                                receivedEOF = buffer[0] == END_TXNL;
                            }
                            else
                            {
                                // Look for FS
                                int fsPos = Array.IndexOf(buffer, (byte)END_TX);

                                if (fsPos == -1) // not found
                                {
                                    continue;
                                }
                                else if (fsPos < buffer.Length - 1) // more room to read
                                {
                                    receivedEOF = buffer[fsPos + 1] == END_TXNL;
                                }
                                else
                                {
                                    scanForCr = true; // Cannot check the end of message for CR because there is no more room in the message buffer
                                }
                                // so need to check on the next loop
                            }
                        }

                        // Use the nHAPI parser to process the data
                        Hl7MessageReceivedEventArgs messageArgs = null;
                        String originalVersion = null;

                        // Setup local and remote receive endpoint data for auditing
                        var localEp        = tcpClient.Client.LocalEndPoint as IPEndPoint;
                        var remoteEp       = tcpClient.Client.RemoteEndPoint as IPEndPoint;
                        Uri localEndpoint  = new Uri(String.Format("llp://{0}:{1}", localEp.Address, localEp.Port));
                        Uri remoteEndpoint = new Uri(String.Format("llp://{0}:{1}", remoteEp.Address, remoteEp.Port));

                        foreach (var messagePart in messageData.ToString().Split((char)END_TX))
                        {
                            if (messagePart == "\r")
                            {
                                continue;
                            }

                            try
                            {
                                this.m_traceSource.TraceInfo("Received message from llp://{0}:{1} : {2}", remoteEp.Address, remoteEp.Port, messagePart);
                                // HACK: nHAPI doesn't like URLs ... Will fix this later
                                string messageString = messagePart.Replace("|URL|", "|ST|");

                                var message = MessageUtils.ParseMessage(messageString, out originalVersion);
                                messageArgs = new Hl7MessageReceivedEventArgs(message, localEndpoint, remoteEndpoint, DateTime.Now);

                                HL7OperationContext.Current = new HL7OperationContext(messageArgs);

                                // Call any bound event handlers that there is a message available
                                OnMessageReceived(messageArgs);
                            }
                            catch (Exception e)
                            {
                                this.m_traceSource.TraceError("Error processing HL7 message: {0}", e);
                                if (messageArgs != null)
                                {
                                    var nack = new NHapi.Model.V25.Message.ACK();
                                    nack.MSH.SetDefault(messageArgs.Message.GetStructure("MSH") as NHapi.Model.V25.Segment.MSH);
                                    nack.MSA.AcknowledgmentCode.Value = "AE";
                                    nack.MSA.TextMessage.Value        = $"FATAL - {e.Message}";
                                    nack.MSA.MessageControlID.Value   = (messageArgs.Message.GetStructure("MSH") as NHapi.Model.V25.Segment.MSH).MessageControlID.Value;
                                    messageArgs.Response = nack;

                                    var icomps = PipeParser.Encode(messageArgs.Message.GetStructure("MSH") as NHapi.Base.Model.ISegment, new EncodingCharacters('|', "^~\\&")).Split('|');
                                    var ocomps = PipeParser.Encode(messageArgs.Response.GetStructure("MSH") as NHapi.Base.Model.ISegment, new EncodingCharacters('|', "^~\\&")).Split('|');
                                    AuditUtil.AuditNetworkRequestFailure(e, messageArgs.ReceiveEndpoint, Enumerable.Range(1, icomps.Length).ToDictionary(o => $"MSH-{o}", o => icomps[o - 1]), Enumerable.Range(1, icomps.Length).ToDictionary(o => $"MSH-{o}", o => ocomps[o - 1]));
                                }
                                else
                                {
                                    AuditUtil.AuditNetworkRequestFailure(e, localEndpoint, new System.Collections.Specialized.NameValueCollection(), new System.Collections.Specialized.NameValueCollection());
                                }
                            }
                            finally
                            {
                                // Send the response back
                                using (MemoryStream memoryWriter = new MemoryStream())
                                {
                                    using (StreamWriter streamWriter = new StreamWriter(memoryWriter))
                                    {
                                        memoryWriter.Write(new byte[] { START_TX }, 0, 1); // header
                                        if (messageArgs != null && messageArgs.Response != null)
                                        {
                                            var strMessage = MessageUtils.EncodeMessage(messageArgs.Response, originalVersion);
                                            this.m_traceSource.TraceInfo("Sending message to llp://{0} : {1}", tcpClient.Client.RemoteEndPoint, strMessage);
                                            // Since nHAPI only emits a string we just send that along the stream
                                            streamWriter.Write(strMessage);
                                            streamWriter.Flush();
                                        }
                                        memoryWriter.Write(new byte[] { END_TX, END_TXNL }, 0, 2); // Finish the stream with FSCR
                                        stream.Write(memoryWriter.ToArray(), 0, (int)memoryWriter.Position);
                                        stream.Flush();
                                    }
                                }
                                lastReceive = DateTime.Now; // Update the last receive time so the timeout function works
                            }
                        }

                        if (!stream.DataAvailable)
                        {
                            return;
                        }
                    }
                }
                catch (Exception e)
                {
                    this.m_traceSource.TraceEvent(EventLevel.Error, e.ToString());
                }
                finally
                {
                    stream.Close();
                    tcpClient.Close();
                    HL7OperationContext.Current = null;
                }
            }
        }
        public RpcAdapterProxy(Type typeToProxy, ITestSite site)
            : base(typeToProxy)
        {
            this.proxiedType = typeToProxy;
            this.site = site;
            this.messageUtils = new MessageUtils(site, Marshaling.NativeMarshalingConfiguration.Configuration);

            RpcAdapterConfig rpcConfig = site.Config.GetAdapterConfig(typeToProxy.Name) as RpcAdapterConfig;
            if (rpcConfig == null)
            {
                throw new InvalidOperationException(String.Format("cannot get adapter config for type '{0}'", typeToProxy.Name));
            }
            this.needAutoValidate = rpcConfig.NeedAutoValidate;

            callingConvention = rpcConfig.CallingConvention;
            charset = rpcConfig.Charset;

            if (!typeof(IRpcAdapter).IsAssignableFrom(proxiedType))
                throw new InvalidOperationException(String.Format("adapter type '{0}' is not an rpc adapter", typeToProxy));

            if (typeof(IRpcImplicitHandleAdapter).IsAssignableFrom(proxiedType))
            {
                getHandleMethod = typeof(IRpcImplicitHandleAdapter).GetMethod("get_Handle");
                setHandleMethod = typeof(IRpcImplicitHandleAdapter).GetMethod("set_Handle");
                handleImplicit = true;
            }
        }
        public async Task SimulateExposureMessage(int notificationTriggerInSeconds = 0)
        {
            await Task.Delay(notificationTriggerInSeconds * 1000);

            await MessageUtils.CreateMessage(this, _messageDateTime);
        }