Example #1
0
        private void UploadMediaObject(string fileName, string type, string title, string obj_value)
        {
            // Copy file sang thu muc Media Object
            fileName = fileName.Replace("/", "\\");
            if (fileName.StartsWith("\\"))
            {
                fileName = fileName.Substring(1);
            }

            if (fileName.ToLower().IndexOf("common") == 0 || fileName.ToLower().IndexOf(HttpContext.Current.User.Identity.Name.ToLower()) == 0)
            {
                int    pos  = fileName.LastIndexOf(@"\");
                string name = "";

                if (pos > 0)
                {
                    name = fileName.Substring(pos + 1);
                }
                else
                {
                    name = fileName;
                }

                string destinationFile = Server.MapPath("~/Images2018/Uploaded/Share");
                if (type == "1")
                {
                    destinationFile += "/Media/Picture/" + name;
                }
                else
                {
                    destinationFile += "/Media/Video/" + name;
                }

                if (!Directory.Exists(Server.MapPath("~/Images2018/Uploaded/Share") + @"/Media/Picture/"))
                {
                    Directory.CreateDirectory(Server.MapPath("~/Images2018/Uploaded/Share") + "/Media/Picture/");
                }

                string sourceFile = Server.MapPath("~/Images/Uploaded") + "/" + fileName;

                if (File.Exists(sourceFile) && !File.Exists(destinationFile))
                {
                    File.Copy(sourceFile, destinationFile);
                }

                destinationFile = destinationFile.Replace("\\", "/");

                fileName = destinationFile.Substring(destinationFile.IndexOf("Share/"));

                // Insert vao DB
                objNewsMediaSource.InsertParameters[0].DefaultValue           = fileName;
                objNewsMediaSource.InsertParameters[1].DefaultValue           = type;
                objNewsMediaSource.InsertParameters[2].DefaultValue           = title;
                objNewsMediaSource.InsertParameters[3].DefaultValue           = ChannelUsers.GetUserName();
                objNewsMediaSource.InsertParameters["obj_value"].DefaultValue = obj_value;
                objNewsMediaSource.Insert();

                isCapNhap = "ok";
            }
        }
Example #2
0
        public static void UpdateUserInfo(string _user_id, string _current_password, string _new_password, string _user_name, string _email, string _address, string _phone, string _ym, string _website)
        {
            UserRow objUser;

            using (DFISYS.User.Db.MainDB objUserDB = new DFISYS.User.Db.MainDB()) {
                objUser = objUserDB.UserCollection.GetByPrimaryKey(_user_id);
            }

            if (objUser != null)
            {
                objUser.User_Address  = _address != null ? _address : "";
                objUser.User_Email    = _email != null ? _email : "";
                objUser.User_Im       = _ym;
                objUser.User_Name     = _user_name;
                objUser.User_PhoneNum = _phone;
                objUser.User_Website  = _website;

                if (_current_password != null && _new_password != null)
                {
                    if (objUser.User_Pwd.Trim() == FormsAuthentication.HashPasswordForStoringInConfigFile(_current_password.Trim(), "MD5") && _new_password.Trim() != "")
                    {
                        objUser.User_Pwd = FormsAuthentication.HashPasswordForStoringInConfigFile(_new_password.Trim(), "MD5");
                    }
                }

                using (DFISYS.User.Db.MainDB objUserDB = new DFISYS.User.Db.MainDB()) {
                    objUserDB.UserCollection.Update(objUser);
                }

                //Cập nhật thời gian thay đổi pass lần cuối cùng
                ChannelUsers.UpdateLastChanged(_user_id, FormsAuthentication.HashPasswordForStoringInConfigFile(_new_password.Trim(), "MD5"));
            }
        }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            PortalDefinition.Tab currentTab = PortalDefinition.GetCurrentTab();
            if (currentTab == null || currentTab.tabs == null)
            {
                return;
            }

            ArrayList tabList = new ArrayList();

            foreach (PortalDefinition.Tab t in currentTab.tabs)
            {
                ChannelUsers objUser = new ChannelUsers();
                if (objUser.HasViewRights(Page.User, t.roles))
                {
                    DisplayTabItem dt = new DisplayTabItem();
                    tabList.Add(dt);

                    dt.m_Text = t.title;
                    dt.m_URL  = "../../" + Portal.API.Config.GetTabURL(t.reference);
                }
            }
            Tabs.DataSource = tabList;
            Tabs.DataBind();
        }
Example #4
0
        public bool DispatchCommand(CommandContext ctx)
        {
            string channelName = ctx.Args.ElementAtOrDefault(1);

            // no error, apparently
            if (string.IsNullOrWhiteSpace(channelName))
            {
                return(false);
            }

            Channels.GetChannelByName(channelName, channel => {
                // the original server sends ForceChannel before sending the error message, but this order probably makes more sense.
                // NEW: REVERT THIS ^^^^ WHEN CONVERTING BACK TO NOT EXCEPTIONS
                // EXCEPTIONS ARE HEAVY, DON'T USE THEM FOR USER ERRORS YOU IDIOT

                if (channel == null)
                {
                    Sessions.SwitchChannel(ctx.Session);
                    throw new ChannelNotFoundCommandException(channelName);
                }

                ChannelUsers.HasUser(channel, ctx.User, hasUser => {
                    if (hasUser)
                    {
                        Sessions.SwitchChannel(ctx.Session);
                        throw new AlreadyInChannelCommandException(channel);
                    }

                    string password = string.Join(' ', ctx.Args.Skip(2));

                    if (!ctx.User.Can(UserPermissions.JoinAnyChannel) && channel.OwnerId != ctx.User.UserId)
                    {
                        if (channel.MinimumRank > ctx.User.Rank)
                        {
                            Sessions.SwitchChannel(ctx.Session);
                            throw new ChannelRankCommandException(channel);
                        }

                        // add capacity check

                        Channels.VerifyPassword(channel, password, success => {
                            if (!success)
                            {
                                Sessions.SwitchChannel(ctx.Session);
                                throw new ChannelPasswordCommandException(channel);
                            }

                            ChannelUsers.JoinChannel(channel, ctx.Session);
                        });
                    }
                    else
                    {
                        ChannelUsers.JoinChannel(channel, ctx.Session);
                    }
                });
            });

            return(true);
        }
Example #5
0
        /// <summary>
        /// Nạp chồng Thủ tục khởi tạo các điều khiển con
        /// </summary>
        override protected void CreateChildControls()
        {
            // Lấy thông tin Tab hiện thời
            PortalDefinition.Tab tab = PortalDefinition.GetCurrentTab();
            if (tab == null)
            {
                return;
            }

            // Kiểm tra quyền của người sử dụng
            ChannelUsers objuser = new ChannelUsers();

            // Edit by Tqdat
            // Xu ly viec khong de Session Timeout la BienTapvien out ra khoi fan Admin
            //  - Neu bi Session TimeOut thi kiem tra xem Cookie co ton tai User va Pass hay ko
            //      + Neu Co thi Login lai de lay lai session
            //      + Neu Khong thi Redirect ra trang login.aspx

            //bool isHasViewRights = objuser.HasViewRights(Page.User, tab.roles);

            /*if (isHasViewRights == false)
             * {
             *  // Kiem tra xem co Cookie hay ko
             *  HttpCookie cookie = Request.Cookies["PortalUser"];
             *  if (cookie != null)
             *  {
             *      objuser.Login(cookie.Values["AC"].Trim(), cookie.Values["PW"].Trim());
             *      isHasViewRights = true;
             *  }
             * }*/

            if (objuser.HasViewRights(Page.User, tab.roles))
            {
                RenderColumns(tab, tab.Columns, DisplayRegion);
                if (IsAdmin)
                {
                    // Hiển thị vùng trắng của các cột rỗng
                    foreach (HtmlTableCell _objEmptyColumn in _arrAllEmptyColumn)
                    {
                        LiteralControl _ltrSpace = new LiteralControl();
                        _ltrSpace.Text = "&nbsp;";
                        _objEmptyColumn.Controls.Add(_ltrSpace);
                    }
                }
            }
            else
            {
                Cache  cache           = new Cache(HttpContext.Current.Application);
                string path            = HttpContext.Current.Request.Url.AbsolutePath.ToLower();
                string _strCacheKey    = Config.GetPortalUniqueCacheKey() + path + "_" + HttpContext.Current.User.Identity.Name;
                string _strCacheRawKey = Config.GetPortalUniqueCacheKey() + "_Raw" + HttpContext.Current.Request.RawUrl + "_" + HttpContext.Current.User.Identity.Name;
                cache[_strCacheKey]    = null;
                cache[_strCacheRawKey] = null;

                Session["NotPermission"] = "True";
                Session["lastPath"]      = HttpContext.Current.Request.RawUrl;
                Response.Redirect("/login.aspx");
            }
        }
Example #6
0
        private void ChannelContinue(PacketHandlerContext ctx, IChannel channel, string text)
        {
            if (channel == null
                //  || !ChannelUsers.HasUser(channel, ctx.User) look below
                //  || (ctx.User.IsSilenced && !ctx.User.Can(UserPermissions.SilenceUser)) TODO: readd silencing
                )
            {
                return;
            }

            ChannelUsers.HasSession(channel, ctx.Session, hasSession => {
                if (!hasSession)
                {
                    return;
                }

                if (ctx.User.Status != UserStatus.Online)
                {
                    Users.Update(ctx.User, status: UserStatus.Online);
                    // ChannelUsers?
                    //channel.SendPacket(new UserUpdatePacket(ctx.User));
                }

                // there's a very miniscule chance that this will return a different value on second read
                int maxLength = Messages.TextMaxLength;
                if (text.Length > maxLength)
                {
                    text = text.Substring(0, maxLength);
                }

                text = text.Trim();

#if DEBUG
                Logger.Write($@"<{ctx.Session.SessionId} {ctx.User.UserName}> {text}");
#endif

                bool handled = false;

                if (text[0] == '/')
                {
                    try {
                        handled = HandleCommand(text, ctx.User, channel, ctx.Session, ctx.Connection);
                    } catch (CommandException ex) {
                        ctx.Connection.SendPacket(ex.ToPacket(Bot));
                        handled = true;
                    }
                }

                if (!handled)
                {
                    Messages.Create(ctx.Session, channel, text);
                }
            });
        }
Example #7
0
        private void ShowSelectedMedia()
        {
            string strNewsId  = Request.QueryString["newsid"] != null ? Request.QueryString["newsid"] : "";
            string str_FilmId = Request.QueryString["pid"] != null ? Request.QueryString["pid"].ToString().Trim() : "";
            string str_Type   = Request.QueryString["type"] != null ? Request.QueryString["type"].ToString().Trim() : "";
            string strWhere   = "";

            if (str_Type.ToLower() == "ShowAll".ToLower())
            {
                strWhere = " AND 1=1";
                //lnkAddMedia.Visible = false;
                //ltrAddMedia.Visible = false;
            }
            else if (strNewsId.Trim() != "")
            {
                string strObject_Id = NewsMediaHelper.Get_ObjectId_By_NewsId(Convert.ToInt64(strNewsId));
                if (strObject_Id.Trim() != "")
                {
                    strWhere = " AND News_Media.Object_ID IN (" + strObject_Id + ")";
                }

                ShowGridCol(5);
            }
            else if (str_FilmId.Trim() != "")
            {
                string strObject_Id = NewsMediaHelper.Get_ObjectId_By_FilmId(str_FilmId);
                if (strObject_Id.Trim() != "")
                {
                    strWhere = " AND News_Media.Object_ID IN (" + strObject_Id + ")";
                }

                ShowGridCol(5);
            }
            else if (Session["Object_Id"] != null && Session["Object_Id"].ToString() != "")
            {
                // Neu Tao Bai viet moi hay tao film moi
                strWhere = " AND News_Media.Object_ID IN (" + Session["Object_Id"].ToString().Substring(1) + ")";
            }
            else
            {
                // Neu Tao moi Film va News Thi khong hien thi Media nao ca
                strWhere = " And News_Media.Object_ID = -2 ";
            }

            if (strWhere.Trim() != "")
            {
                objNewsMediaSource.SelectParameters[0].DefaultValue = "UserID='" + ChannelUsers.GetUserName() + "'" + strWhere;
            }
            else
            {
                objNewsMediaSource.SelectParameters[0].DefaultValue = "UserID='" + ChannelUsers.GetUserName() + "'" + " AND News_Media.Object_ID = -1 ";
            }
        }
Example #8
0
        async Task <bool> IPermissionConfig.RemoveSpecialUser(ITextChannel channel, IGuildUser user)
        {
            var cu = await QuerySpecialUsers()
                     .SingleOrDefaultAsync(u => u.Channel.ChannelId == channel.Id && u.User.UserId == user.Id).ConfigureAwait(false);

            if (cu != null)
            {
                ChannelUsers.Remove(cu);
                await SaveChangesAsync().ConfigureAwait(false);

                return(true);
            }
            return(false);
        }
        public void HandleCommand(ClientCommandContext ctx)
        {
            string channelName = ctx.Arguments.ElementAtOrDefault(0);

            if (string.IsNullOrWhiteSpace(channelName))
            {
                ctx.Connection.SendReply(new NoRecipientReply(NAME));
                return;
            }

            string text = ctx.Arguments.ElementAtOrDefault(1);

            if (string.IsNullOrWhiteSpace(text))
            {
                ctx.Connection.SendReply(new NoTextToSendReply());
                return;
            }

            Func <IChannel, bool> predicate = null;
            char channelPrefix = channelName.First();

            if (channelPrefix == '#')
            {
                predicate = new Func <IChannel, bool>(c => channelName.Equals(c.GetIRCName()));
            }

            if (predicate == null)
            {
                ctx.Connection.SendReply(new NoSuchNickReply(channelName));
                return;
            }

            Channels.GetChannel(predicate, channel => {
                if (channel == null)
                {
                    ctx.Connection.SendReply(new NoSuchNickReply(channelName));
                    return;
                }

                ChannelUsers.HasUser(channel, ctx.User, hasUser => {
                    if (!hasUser)
                    {
                        ctx.Connection.SendReply(new CannotSendToChannelReply(channel));
                        return;
                    }

                    Messages.Create(ctx.Session, channel, text);
                });
            });
        }
        private void RemoveChannelOperator(MODERequest cmd)
        {
            var result = ChannelUsers.Where(u => u.UserInfo.UserName == cmd.UserName);

            if (result.Count() != 1)
            {
                return;
            }
            ChatChannelUser user = result.First();

            if (user.IsChannelCreator)
            {
                user.SetChannelCreator(false);
            }
        }
Example #11
0
        public bool DispatchCommand(CommandContext ctx)
        {
            if (!ctx.User.Can(UserPermissions.CreateChannel))
            {
                throw new CommandNotAllowedException(NAME);
            }

            bool hasRank;

            if (ctx.Args.Count() < 2 || (hasRank = ctx.Args.ElementAtOrDefault(1)?.All(char.IsDigit) == true && ctx.Args.Count() < 3))
            {
                throw new CommandFormatException();
            }

            int rank = 0;

            if (hasRank && !int.TryParse(ctx.Args.ElementAtOrDefault(1), out rank) && rank < 0)
            {
                rank = 0;
            }

            if (rank > ctx.User.Rank)
            {
                throw new InsufficientRankForChangeCommandException();
            }

            string   createChanName = string.Join('_', ctx.Args.Skip(hasRank ? 2 : 1));
            IChannel createChan;

            try {
                createChan = Channels.Create(
                    ctx.User,
                    createChanName,
                    null,
                    !ctx.User.Can(UserPermissions.SetChannelPermanent),
                    rank
                    );
            } catch (ChannelExistException) {
                throw new ChannelExistsCommandException(createChanName);
            } catch (ChannelInvalidNameException) {
                throw new ChannelNameInvalidCommandException();
            }

            ChannelUsers.JoinChannel(createChan, ctx.Session);

            ctx.Connection.SendPacket(new ChannelCreateResponsePacket(Sender, createChan));
            return(true);
        }
        private void DisableUserVoicePermission(MODERequest cmd)
        {
            var result = ChannelUsers.Where(u => u.UserInfo.UserName == cmd.UserName);

            if (result.Count() != 1)
            {
                return;
            }

            ChatChannelUser user = result.First();

            if (user.IsVoiceable)
            {
                user.SetVoicePermission(false);
            }
        }
Example #13
0
        // should this be moved to UserManager?
        public void BanUser(
            IUser user,
            TimeSpan duration,
            UserDisconnectReason reason = UserDisconnectReason.Kicked,
            bool isPermanent            = false,
            IUser modUser     = null,
            string textReason = null
            )
        {
            ForceDisconnectPacket packet;

            if (duration != TimeSpan.Zero || isPermanent)
            {
                if (string.IsNullOrWhiteSpace(textReason))
                {
                    textReason = reason switch {
                        UserDisconnectReason.Kicked => @"User was banned.",
                        UserDisconnectReason.Flood => @"User was kicked for flood protection.",
                        _ => @"Unknown reason given.",
                    }
                }
                ;

                DataProvider.BanClient.CreateBan(user.UserId, modUser?.UserId ?? -1, isPermanent, duration, textReason);

                packet = new ForceDisconnectPacket(ForceDisconnectReason.Banned, duration, isPermanent);
            }
            else
            {
                packet = new ForceDisconnectPacket(ForceDisconnectReason.Kicked);
            }

            // handle in users
            //user.SendPacket(packet);

            // channel users
            ChannelUsers.GetChannels(user, c => {
                foreach (IChannel chan in c)
                {
                    ChannelUsers.LeaveChannel(chan, user, reason);
                }
            });

            // a disconnect with Flood, Kicked or Banned should probably cause this
            // maybe forced disconnects should be their own event?
            Users.Disconnect(user, reason);
        }
        private void AddBanOnUser(MODERequest cmd)
        {
            var result = ChannelUsers.Where(u => u.UserInfo.NickName == cmd.NickName);

            if (result.Count() != 1)
            {
                return;
            }
            ChatChannelUser user = result.First();

            if (BanList.Where(u => u.UserInfo.NickName == cmd.NickName).Count() == 1)
            {
                return;
            }

            BanList.Add(user);
        }
Example #15
0
        public void DispatchEvent(object sender, IEvent evt)
        {
            if (evt == null)
            {
                throw new ArgumentNullException(nameof(evt));
            }

            lock (Sync) {
                Logger.Debug(evt);

                Sessions.HandleEvent(sender, evt);
                Users.HandleEvent(sender, evt);
                Channels.HandleEvent(sender, evt);
                ChannelUsers.HandleEvent(sender, evt);
                Messages.HandleEvent(sender, evt);
            }
        }
Example #16
0
        public bool DispatchCommand(ICommandContext ctx)
        {
            string channelName = ctx.Args.ElementAtOrDefault(1);

            // no error, apparently
            if (string.IsNullOrWhiteSpace(channelName))
            {
                return(false);
            }

            IChannel channel = Channels.GetChannel(channelName);

            // the original server sends ForceChannel before sending the error message, but this order probably makes more sense.

            if (channel == null)
            {
                Sessions.SwitchChannel(ctx.Session);
                throw new ChannelNotFoundCommandException(channelName);
            }

            if (ChannelUsers.HasUser(channel, ctx.User))
            {
                Sessions.SwitchChannel(ctx.Session);
                throw new AlreadyInChannelCommandException(channel);
            }

            string password = string.Join(' ', ctx.Args.Skip(2));

            if (!ctx.User.Can(UserPermissions.JoinAnyChannel) && channel.Owner != ctx.User)
            {
                if (channel.MinimumRank > ctx.User.Rank)
                {
                    Sessions.SwitchChannel(ctx.Session);
                    throw new ChannelRankCommandException(channel);
                }

                if (channel.VerifyPassword(password))
                {
                    Sessions.SwitchChannel(ctx.Session);
                    throw new ChannelPasswordCommandException(channel);
                }
            }

            ChannelUsers.JoinChannel(channel, ctx.Session);
            return(true);
        }
        private void AddChannelOperator(MODERequest cmd)
        {
            // check whether this user is in this channel
            var result = ChannelUsers.Where(u => u.UserInfo.UserName == cmd.UserName);

            if (result.Count() != 1)
            {
                return;
            }
            ChatChannelUser user = result.First();

            //if this user is already in operator we do not add it
            if (user.IsChannelOperator)
            {
                return;
            }
            user.SetChannelOperator(true);
        }
Example #18
0
        public async Task JoinChannel(int channelID)
        {
            var userId = Context.UserIdentifier;
            var CU     = await _dbContext.ChannelUsers.SingleOrDefaultAsync(cu => cu.UserID == userId && cu.ChannelID == channelID);

            var channel = await _dbContext.Channels.SingleOrDefaultAsync(c => c.ID == channelID);

            if (userId == null)
            {
                return;
            }

            if (CU.Channel.EnableWhitelist)
            {
                var CG = await _dbContext.ChannelGroups.Where(cg => cg.ChannelID == channelID).ToListAsync();

                var hasRole = false;
                foreach (var group in CG)
                {
                    if (Context.User.IsInRole(group.Group.Name))
                    {
                        hasRole = true;
                    }
                }
                if (hasRole || CU.Status == 1)
                {
                    CU.isJoined = true;
                    _dbContext.Entry(CU).State = EntityState.Modified;
                }
                else
                {
                    return;
                }
            }
            else
            {
                CU = new ChannelUsers {
                    ChannelID = channelID, UserID = userId, isJoined = true, Status = 0
                };
                _dbContext.Add(CU);
            }

            await _dbContext.SaveChangesAsync();
        }
Example #19
0
        async Task <bool> IPermissionConfig.AddSpecialUser(ITextChannel channel, IGuildUser user)
        {
            var cu = QuerySpecialUsers().SingleOrDefault(s => s.Channel.ChannelId == channel.Id && s.User.UserId == user.Id);

            if (cu == null)
            {
                var ch = QueryChannel(channel);
                var sp = QueryUser(user) ?? await AddUserInternal(user).ConfigureAwait(false);

                cu = new ChannelUser <TChannel, TUser>
                {
                    Channel = ch,
                    User    = sp
                };
                ChannelUsers.Add(cu);
                await SaveChangesAsync().ConfigureAwait(false);

                return(true);
            }
            return(false);
        }
Example #20
0
        public void SendMessage(string msg)
        {
            if (!msg.StartsWith("/"))
            {
                bnetConnection.SendMessage(msg);

                var chatMsg = new BnetEvent();
                chatMsg.EventId   = 0x18;
                chatMsg.Message   = msg;
                chatMsg.Username  = bnetAccount.Username;
                chatMsg.TimeStamp = DateTime.Now;
                ChatMessages.Add(chatMsg);

                Messenger.Default.Send <ScrollDownMessage>(new ScrollDownMessage()
                {
                    Source = this
                });
            }
            else
            {
                if (msg.ToLower() == "/reconnect")
                {
                    ChannelUsers.Clear();
                    ChannelList.Clear();
                    FriendsList.Clear();

                    ChattingStatus = "disconnected";
                    Connect();
                }
                else if (msg.ToLower() == "/version")
                {
                    bnetConnection.SendMessage("/me is using Superiority.NET Beta5 (www.BNET.cc).");
                }
                else
                {
                    bnetConnection.SendMessage(msg);
                }
            }
        }
        private void WriteCookie(string path)
        {
            HttpCookie myCookie = new HttpCookie("fl");
            DateTime   now      = DateTime.Now;

            string userName = ChannelUsers.GetUserName();

            if (path.Contains(userName))
            {
                path = path.Substring(path.IndexOf(userName) + userName.Length);
            }
            else
            {
                path = "Common";
            }

            // Set the cookie value.
            myCookie.Value = Crypto.EncryptForHTML(path);
            // Set the cookie expiration date.
            myCookie.Expires = now.AddMonths(1);

            // Add the cookie.
            Response.Cookies.Add(myCookie);
        }
        /// <summary>
        /// Nạp chồng Thủ tục khởi tạo các điều khiển con
        /// </summary>
        override protected void CreateChildControls()
        {
            // Lấy thông tin Tab hiện thời
            PortalDefinition.Tab tab = PortalDefinition.GetCurrentTab();
            if (tab == null)
            {
                return;
            }

            // Kiểm tra quyền của người sử dụng
            ChannelUsers objuser = new ChannelUsers();


            if (objuser.HasViewRights(Page.User, tab.roles))
            {
                // Tiến hành sinh mã cho các cột của Tab
                // Vùng bắt đầu là DisplayRegion.
                RenderColumns(tab, tab.Columns, DisplayRegion);
            }
            else
            {
                // Add by tqdat
                Cache  cache           = new Cache(HttpContext.Current.Application);
                string path            = HttpContext.Current.Request.Url.AbsolutePath.ToLower();
                string _strCacheKey    = Config.GetPortalUniqueCacheKey() + path + "_" + HttpContext.Current.User.Identity.Name;
                string _strCacheRawKey = Config.GetPortalUniqueCacheKey() + "_Raw" + HttpContext.Current.Request.RawUrl + "_" + HttpContext.Current.User.Identity.Name;
                cache[_strCacheKey]    = null;
                cache[_strCacheRawKey] = null;
                Session["lastPath"]    = HttpContext.Current.Request.RawUrl;


                // Neu khong duoc fep access vao hoac Mat Session thi redirect ve trang Login

                Response.Redirect("/login.aspx");
            }
        }
Example #23
0
        private void WhoChannel(ICommandContext ctx, string channelName)
        {
            IChannel channel = Channels.GetChannel(channelName);

            if (channel == null)
            {
                throw new ChannelNotFoundCommandException(channelName);
            }

            if (channel.MinimumRank > ctx.User.Rank || (channel.HasPassword && !ctx.User.Can(UserPermissions.JoinAnyChannel)))
            {
                throw new UserListChannelNotFoundCommandException(channelName);
            }

            ChannelUsers.GetUsers(
                channel,
                users => ctx.Session.SendPacket(new UserListResponsePacket(
                                                    Sender,
                                                    channel,
                                                    ctx.User,
                                                    users.OrderByDescending(u => u.Rank)
                                                    ))
                );
        }
Example #24
0
 void irc_channelUsers(string thisChannel, string[] channelUsers)
 {
     if (this.textBoxUsers.InvokeRequired)
     {
         // It's on a different thread, so use Invoke.
         ChannelUsers d = new ChannelUsers(populateUsers);
         this.Invoke
             (d, new object[] { thisChannel, channelUsers });
     }
     else
     {
         // It's on the same thread, no need for Invoke
         populateUsers(thisChannel, channelUsers);
     }
 }
Example #25
0
        public void HandlePacket(PacketHandlerContext ctx)
        {
            if (ctx.HasSession)
            {
                return;
            }

            if (!long.TryParse(ctx.Args.ElementAtOrDefault(1), out long userId) || userId < 1)
            {
                return;
            }

            string token = ctx.Args.ElementAtOrDefault(2);

            if (string.IsNullOrEmpty(token))
            {
                return;
            }

            Action <Exception> exceptionHandler = new Action <Exception>(ex => {
                Logger.Debug($@"[{ctx.Connection}] Auth fail: {ex.Message}");
                ctx.Connection.SendPacket(new AuthFailPacket(AuthFailReason.AuthInvalid));
                ctx.Connection.Close();
            });

            DataProvider.UserAuthClient.AttemptAuth(
                new UserAuthRequest(userId, token, ctx.Connection.RemoteAddress),
                res => {
                DataProvider.BanClient.CheckBan(res.UserId, ctx.Connection.RemoteAddress, ban => {
                    if (ban.IsPermanent || ban.Expires > DateTimeOffset.Now)
                    {
                        ctx.Connection.SendPacket(new AuthFailPacket(AuthFailReason.Banned, ban));
                        ctx.Connection.Close();
                        return;
                    }

                    Users.Connect(res, user => {
                        Sessions.HasAvailableSessions(user, available => {
                            if (!available)
                            {
                                ctx.Connection.SendPacket(new AuthFailPacket(AuthFailReason.MaxSessions));
                                ctx.Connection.Close();
                                return;
                            }

                            Sessions.Create(ctx.Connection, user, session => {
                                string welcome = Server.WelcomeMessage;
                                if (!string.IsNullOrWhiteSpace(welcome))
                                {
                                    ctx.Connection.SendPacket(new WelcomeMessagePacket(Sender, welcome.Replace(@"{username}", user.UserName)));
                                }

                                if (WelcomeMessage.HasRandom)
                                {
                                    string line = WelcomeMessage.GetRandomString();
                                    if (!string.IsNullOrWhiteSpace(line))
                                    {
                                        ctx.Connection.SendPacket(new WelcomeMessagePacket(Sender, line));
                                    }
                                }

                                Channels.GetDefaultChannels(channels => {
                                    if (!channels.Any())
                                    {
                                        return;     // what do, this is impossible
                                    }
                                    // other channels should be joined if MCHAN has been received
                                    IChannel firstChan = channels.FirstOrDefault();

                                    ctx.Connection.LastChannel = firstChan;
                                    ctx.Connection.SendPacket(new AuthSuccessPacket(user, firstChan, session, Messages.TextMaxLength));

                                    Channels.GetChannels(user.Rank, c => ctx.Connection.SendPacket(new ContextChannelsPacket(c)));
                                    ChannelUsers.JoinChannel(firstChan, ctx.Session);
                                });
                            });
                        });
                    });
                }, exceptionHandler);
            },
                exceptionHandler
                );
        }
Example #26
0
 protected void lnkShowAllMedia_Click(object sender, EventArgs e)
 {
     objNewsMediaSource.SelectParameters[0].DefaultValue = "UserID='" + ChannelUsers.GetUserName() + "' ";
 }
Example #27
0
        protected void grdMedia_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.ToLower() == "NewMediaObject".ToLower())
            {
                GridViewRow grdrow = this.grdMedia.FooterRow;
                if (grdrow != null)
                {
                    TextBox      txtINote = grdrow.FindControl("txtINote") as TextBox;
                    DropDownList cboType  = grdrow.FindControl("cboIType") as DropDownList;
                    FileUpload   flObject = grdrow.FindControl("flObject") as FileUpload;
                    if (cboType != null)
                    {
                        if (flObject.FileName != "")
                        {
                            objNewsMediaSource.InsertParameters[0].DefaultValue = flObject.FileName;
                            objNewsMediaSource.InsertParameters[1].DefaultValue = cboType.SelectedValue;
                            objNewsMediaSource.InsertParameters[2].DefaultValue = txtINote.Text;
                            objNewsMediaSource.InsertParameters[3].DefaultValue = ChannelUsers.GetUserName();
                            objNewsMediaSource.Insert();
                            //thuc hien upload anh vao thu muc Share

                            if (DFISYS.FileHelper.isFileMediaObject(flObject.FileName))
                            {
                                //duong dan den thu muc upload1
                                string strFolder = "Images2018/Uploaded/";
                                string strType   = "Picture";
                                if (cboType.SelectedValue != "1")
                                {
                                    strType = "Video";
                                }
                                string strFileUploaded = DFISYS.FileHelper.UploadMediaObject(strFolder, "Share/Media/" + strType, flObject.PostedFile, 125);
                            }
                        }

                        //ShowSelectedMedia();
                        //grdMedia.DataBind();
                    }
                }
            }

            if (e.CommandName.ToLower() == "DeleteMedia".ToLower())
            {
                string str_MediaId = e.CommandArgument.ToString().Trim();
                string str_Newsid  = Request.QueryString["newsid"] != null ? Request.QueryString["newsid"].ToString().Trim() : "";
                string str_FilmId  = Request.QueryString["filmid"] != null ? Request.QueryString["filmid"].ToString().Trim() : "";

                /*
                 * if (str_Newsid.Trim() != "")
                 * {
                 *  NewsMediaHelper.Delete_News_Media_ByNewsIdAndObjectId(Convert.ToInt64(str_Newsid), str_MediaId);
                 *
                 * }
                 * else
                 * if (str_FilmId.Trim() != "")
                 * {
                 *  NewsMediaHelper.DeleteNews_Media_Film_Object_By_FilmIdAndObjectId(Convert.ToInt32(str_FilmId), Convert.ToInt32(str_MediaId));
                 *
                 *
                 * }
                 */

                if (NewsMediaHelper.Check_Exist_News_Media_ByObjectId(str_MediaId))
                {
                    Page.RegisterClientScriptBlock("CannotDeleteImage", "<script language='javascript'>alert('Có một số image bạn không thể xóa được !');</script>");
                }
                else
                {
                    // Neu khong dc su dung thi co the xoa di duoc
                    objNewsMediaSource.DeleteParameters[0].DefaultValue = str_MediaId;
                    objNewsMediaSource.Delete();
                }

                grdMedia.DataBind();
            }
        }
Example #28
0
        public void HandlePacket(IPacketHandlerContext ctx)
        {
            if (ctx.HasSession)
            {
                return;
            }

            if (!long.TryParse(ctx.Args.ElementAtOrDefault(1), out long userId) || userId < 1)
            {
                return;
            }

            string token = ctx.Args.ElementAtOrDefault(2);

            if (string.IsNullOrEmpty(token))
            {
                return;
            }

            Action <Exception> exceptionHandler = new Action <Exception>(ex => {
                Logger.Debug($@"<{ctx.Connection.RemoteAddress}> Auth fail: {ex.Message}");
                ctx.Connection.Send(new AuthFailPacket(AuthFailReason.AuthInvalid));
                ctx.Connection.Close();
            });

            DataProvider.UserAuthClient.AttemptAuth(
                new UserAuthRequest(userId, token, ctx.Connection.RemoteAddress),
                res => {
                DataProvider.BanClient.CheckBan(res.UserId, ctx.Connection.RemoteAddress, ban => {
                    if (ban.IsPermanent || ban.Expires > DateTimeOffset.Now)
                    {
                        ctx.Connection.Send(new AuthFailPacket(AuthFailReason.Banned, ban));
                        ctx.Connection.Close();
                        return;
                    }

                    IUser user = Users.Connect(res);

                    // Enforce a maximum amount of connections per user
                    if (Sessions.GetAvailableSessionCount(user) < 1)
                    {
                        ctx.Connection.Send(new AuthFailPacket(AuthFailReason.MaxSessions));
                        ctx.Connection.Close();
                        return;
                    }

                    ISession sess = Sessions.Create(ctx.Connection, user);

                    sess.SendPacket(new WelcomeMessagePacket(Sender, $@"Welcome to Flashii Chat, {user.UserName}!"));

                    if (File.Exists(WELCOME))
                    {
                        IEnumerable <string> lines = File.ReadAllLines(WELCOME).Where(x => !string.IsNullOrWhiteSpace(x));
                        string line = lines.ElementAtOrDefault(RNG.Next(lines.Count()));

                        if (!string.IsNullOrWhiteSpace(line))
                        {
                            sess.SendPacket(new WelcomeMessagePacket(Sender, line));
                        }
                    }

                    IChannel chan   = Channels.DefaultChannel;
                    bool shouldJoin = !ChannelUsers.HasUser(chan, user);

                    if (shouldJoin)
                    {
                        // ChannelUsers?
                        //chan.SendPacket(new UserConnectPacket(DateTimeOffset.Now, user));
                        //ctx.Chat.DispatchEvent(this, new UserConnectEvent(chan, user));
                    }

                    sess.SendPacket(new AuthSuccessPacket(user, chan, sess, Version, Messages.TextMaxLength));
                    ChannelUsers.GetUsers(chan, u => sess.SendPacket(new ContextUsersPacket(u.Except(new[] { user }).OrderByDescending(u => u.Rank))));

                    Messages.GetMessages(chan, m => {
                        foreach (IMessage msg in m)
                        {
                            sess.SendPacket(new ContextMessagePacket(msg));
                        }
                    });

                    Channels.GetChannels(user.Rank, c => sess.SendPacket(new ContextChannelsPacket(c)));

                    if (shouldJoin)
                    {
                        ChannelUsers.JoinChannel(chan, sess);
                    }
                }, exceptionHandler);
            },
                exceptionHandler
                );
        }
Example #29
0
 private IQueryable <ChannelUser <TChannel, TUser> > QuerySpecialUsers()
 => ChannelUsers.Include(cu => cu.Channel).Include(cu => cu.User);
        public void HandlePacket(IPacketHandlerContext ctx)
        {
            if (ctx.Args.Count() < 3 || !ctx.HasUser || !ctx.User.Can(UserPermissions.SendMessage))
            {
                return;
            }

            if (!long.TryParse(ctx.Args.ElementAtOrDefault(1), out long userId) || ctx.User.UserId != userId)
            {
                return;
            }

            // No longer concats everything after index 1 with \t, no previous implementation did that either
            string text = ctx.Args.ElementAtOrDefault(2);

            if (string.IsNullOrWhiteSpace(text))
            {
                return;
            }

            IChannel channel;
            string   channelName = ctx.Args.ElementAtOrDefault(3)?.ToLowerInvariant();

            if (string.IsNullOrWhiteSpace(channelName))
            {
                channel = Channels.DefaultChannel;
            }
            else
            {
                channel = Channels.GetChannel(channelName);
            }

            if (channel == null ||
                !ChannelUsers.HasUser(channel, ctx.User)
                //  || (ctx.User.IsSilenced && !ctx.User.Can(UserPermissions.SilenceUser)) TODO: readd silencing
                )
            {
                return;
            }

            if (ctx.User.Status != UserStatus.Online)
            {
                Users.Update(ctx.User, status: UserStatus.Online);
                // ChannelUsers?
                //channel.SendPacket(new UserUpdatePacket(ctx.User));
            }

            // there's a very miniscule chance that this will return a different value on second read
            int maxLength = Messages.TextMaxLength;

            if (text.Length > maxLength)
            {
                text = text.Substring(0, maxLength);
            }

            text = text.Trim();

#if DEBUG
            Logger.Write($@"<{ctx.Session.SessionId} {ctx.User.UserName}> {text}");
#endif

            bool handled = false;

            if (text[0] == '/')
            {
                try {
                    handled = HandleCommand(text, ctx.User, channel, ctx.Session);
                } catch (CommandException ex) {
                    ctx.Session.SendPacket(ex.ToPacket(Bot));
                    handled = true;
                }
            }

            if (!handled)
            {
                Messages.Create(ctx.User, channel, text);
            }
        }
Example #31
0
        /// <summary>
        /// Thủ tục khởi tạo Module và chèn Module vào cột đã định.
        /// </summary>
        /// <param name="td">Ô (hay cột) chứa Module</param>
        /// <param name="tab">Tab chứa Module (cần để lấy thêm thông tin về Tab)</param>
        /// <param name="modules">Danh sách Module đã được định nghĩa thuộc cột này</param>
        private void RenderModules(HtmlTableCell td, PortalDefinition.Tab tab, ArrayList modules)
        {
            //if (Request.HttpMethod == "GET")
            //{

            // Kiểm tra nếu không có Module nào trong cột thì chèn khoảng trắng để lưu vị trí cột
            if (modules.Count == 0)
            {
                _arrAllEmptyColumn.Add(td);
            }
            // Duyệt danh sách Module
            PortalDefinition.Module _objModuleDefinition;
            ChannelUsers            objUser = new ChannelUsers();
            // Khởi tạo Module
            Module       _objModuleControl;
            CachedModule _objCachedModuleControl;

            for (int _intModuleCount = 0; _intModuleCount < modules.Count; _intModuleCount++)
            {
                _objModuleDefinition = modules[_intModuleCount] as PortalDefinition.Module;
                //DuongNA tạm thời bỏ Kiểm tra người dùng có quyền hiển thị Module hay không
                //if (objUser.HasViewRights(Page.User, _objModuleDefinition.roles))
                {
                    _objModuleControl       = null;
                    _objCachedModuleControl = null;
                    // Nạp các thông số về Module
                    _objModuleDefinition.LoadModuleSettings();
                    //DuongNA tạm thời bỏ trycatch
                    //try
                    {
                        // Kiểm tra xem có thông số nào được xác lập không
                        // Xây dựng chuỗi đường dẫn đến tệp ASCX
                        string _strModuleSrc = Config.GetModuleVirtualPath(_objModuleDefinition.type);
                        if (_objModuleDefinition.moduleSettings == null)
                        {
                            string[] strModulePath = _objModuleDefinition.type.Split("/".ToCharArray());
                            string   strModule;
                            if (strModulePath.Length == 2)
                            {
                                strModule = strModulePath[1];
                            }
                            else
                            {
                                strModule = strModulePath[0];
                            }
                            _strModuleSrc += strModule + ".ascx";
                        }
                        else
                        {
                            _strModuleSrc += _objModuleDefinition.moduleSettings.ctrl;
                        }


                        //DuongNA tạm thời bỏ Kiểm tra xem Module có được phép hiển thị hay không
                        //if((_objModuleControl != null && _objModuleControl.IsVisible() || (_objCachedModuleControl != null && _objCachedModuleControl.IsVisible())))
                        {
                            // Kiểm tra xem trang hiện thời có nằm trong trạng thái cho phép kéo thả hay không
                            // Nếu ở trạng thái hỗ trợ kéo thả thì tạo các khung chứa (Snap) để chứa nội dung của các Module
                            // (nội dung này sẽ được nạp sử dụng Ajax khi người sử dụng mở rộng khung hoặc chế độ tự động mở rộng khung dc bật)

                            if (_objModuleDefinition.CacheTime <= 0)
                            {
                                // Nếu Module không sử dụng Cache
                                _objModuleControl = (Module)LoadModule(_strModuleSrc);

                                // Khởi tạo nội dung Module
                                _objModuleControl.InitModule(tab.reference,
                                                             _objModuleDefinition.reference,
                                                             _objModuleDefinition.type,
                                                             Config.GetModuleVirtualPath(_objModuleDefinition.type),
                                                             true);
                            }
                            else
                            {
                                // Nếu Module có sử dụng Cache
                                _objCachedModuleControl = new CachedModule();
                                _objCachedModuleControl.ModuleCacheTime = _objModuleDefinition.CacheTime;

                                // Khởi tạo nội dung Module
                                _objCachedModuleControl.InitModule(tab.reference,
                                                                   _objModuleDefinition.reference,
                                                                   _objModuleDefinition.type,
                                                                   Config.GetModuleVirtualPath(_objModuleDefinition.type),
                                                                   true,
                                                                   _strModuleSrc);
                            }

                            if ((_objModuleControl != null && _objModuleControl.IsVisible() || (_objCachedModuleControl != null && _objCachedModuleControl.IsVisible())))
                            {
                                // Hiển thị nội dung Module theo cách trình bày bình thường không hỗ trợ kéo thả
                                HtmlTable _objSimpleModuleContainer = new HtmlTable();
                                _objSimpleModuleContainer.Width       = "100%";
                                _objSimpleModuleContainer.CellPadding = 0;
                                _objSimpleModuleContainer.CellSpacing = 0;
                                _objSimpleModuleContainer.Rows.Add(new HtmlTableRow());

                                // Nạp dữ liệu của Module vào ô chứa Module
                                HtmlTableCell _objCellContainer = new HtmlTableCell();
                                _objSimpleModuleContainer.Rows[0].Cells.Add(_objCellContainer);
                                _objCellContainer.Attributes.Add("class", "Module_Simple_Block");
                                _objCellContainer.VAlign = "top";
                                if (_objModuleControl != null)
                                {
                                    _objCellContainer.Controls.Add(_objModuleControl);
                                }
                                else
                                {
                                    _objCellContainer.Controls.Add(_objCachedModuleControl);
                                }
                                //cách giữa header và body
                                _objCellContainer.Attributes.Add("style", "padding-bottom:0px;");
                                td.Controls.Add(_objSimpleModuleContainer);
                            }

                            //}
                        }
                    }
                    //catch (Exception e)
                    //{
                    //    Console.WriteLine(e.Message + e.StackTrace);
                    //}
                }
            }
        }