Inheritance: MonoBehaviour
Ejemplo n.º 1
0
    /// <summary>
    /// 组装显示在前台好友列表的HTML
    /// </summary>
    /// <param name="list">好友列表</param>
    /// <returns>HTML字符串</returns>
    private string MakeUnorderListString(FriendList list)
    {
        string htmlStr = "<table width=100% id='tblFriendList'>";

        foreach(FriendItem item in list)
        {
            UserItem friend=new UsersOperator().LoadUser(item.FriendId);
            string liStr = "<tr width=100% valign=top>";

            liStr += string.Format("<td><img src='{0}' id='{1}' onclick='friendFaceDbClick()' />", "faces/" + friend.FaceId.ToString() + ".bmp", friend.Id);
            liStr+=friend.NickName;
            liStr += "</td></tr>";
            htmlStr += liStr;
        }
        htmlStr += "</table>";

        return htmlStr;
    }
Ejemplo n.º 2
0
        public FriendListViewModel CreateFriendListViewModel(FriendList friendList, Action refreshFriendListAction)
        {
            var friendListViewModel = new FriendListViewModel()
            {
                FriendListItems = new ObservableCollection <FriendListItem>()
            };

            var acceptFriendCommand = new AcceptFriendRequestCommand(friendListViewModel, refreshFriendListAction, _friendService, _logger);
            var removeFriendCommand = new RemoveFriendCommand(friendListViewModel, refreshFriendListAction, _friendService, _logger);

            foreach (var incomingRequest in friendList.IncomingRequests)
            {
                friendListViewModel.FriendListItems.Add(MapFriendRequestToViewModel(incomingRequest, acceptFriendCommand, removeFriendCommand));
            }

            foreach (var friend in friendList.Friends.Where(t => t.IsOnline))
            {
                friendListViewModel.FriendListItems.Add(MapFriendToViewModel(friend, removeFriendCommand));
            }

            foreach (var friend in friendList.Friends.Where(t => !t.IsOnline))
            {
                friendListViewModel.FriendListItems.Add(MapFriendToViewModel(friend, removeFriendCommand));
            }

            friendListViewModel.FriendListItems.Add(new FriendListSeparator());

            foreach (var outgoingRequest in friendList.OutgoingRequests)
            {
                friendListViewModel.FriendListItems.Add(MapOutoingFriendRequest(outgoingRequest, removeFriendCommand));
            }

            friendListViewModel.OnlineFriendsCount = friendListViewModel.FriendListItems.Count(t => t is OnlineFriend);
            friendListViewModel.FriendListCount    = friendList.Friends.Count;

            return(friendListViewModel);
        }
Ejemplo n.º 3
0
        // GET: Profile/?userName=userName
        public ActionResult Index(string userName)
        {
            Account account = Session["account"] as Account;

            if (account == null)
            {
                TempData["infoMsg"] = "You must be logged in.";
                return(RedirectToAction("", "Login"));
            }
            if (userName == null)
            {
                throw new HttpException(400, "Bad request");
            }
            Person person = db.People.Where(p => p.Account.userName == userName).SingleOrDefault();

            if (person == null)
            {
                throw new HttpException(404, "Not found");
            }
            FriendList friendList = db.FriendLists.Where(fl => fl.personId == account.personId && fl.friendId == person.personId).SingleOrDefault();

            ViewBag.isFriend = friendList != null;
            return(View(person));
        }
Ejemplo n.º 4
0
        public static async void OnClientConnect(object sender, ConnectEventArgs args)
        {
            var f = await args.SoraApi.GetFriendList();

            if (f.apiStatus == APIStatusType.OK)
            {
                FriendList.RefreshList(args.LoginUid, f.friendList);
            }
            var g = await args.SoraApi.GetGroupList();

            if (g.apiStatus == APIStatusType.OK)
            {
                GroupList.RefreshList(args.LoginUid, g.groupList);
                foreach (var group in g.groupList)
                {
                    var gm = await args.SoraApi.GetGroupMemberList(group.GroupId);

                    if (gm.apiStatus == APIStatusType.OK)
                    {
                        GroupList.RefreshMemberList(group.GroupId, gm.groupMemberList);
                    }
                }
            }
        }
Ejemplo n.º 5
0
 public void onLowMemory()
 {
     FriendList.onLowMemory();
 }
Ejemplo n.º 6
0
        private bool sendMessage(Friend friend, PendingMessage pending_message, bool add_to_pending_messages = true)
        {
            StreamMessage msg                    = pending_message.streamMessage;
            bool          send_to_server         = pending_message.sendToServer;
            bool          send_push_notification = pending_message.sendPushNotification;

            // TODO this function has to be improved and node's wallet address has to be added
            if (friend.publicKey != null || (msg.encryptionType != StreamMessageEncryptionCode.rsa && friend.aesKey != null && friend.chachaKey != null))
            {
                if (msg.encryptionType == StreamMessageEncryptionCode.none)
                {
                    if (friend.aesKey != null && friend.chachaKey != null)
                    {
                        // upgrade encryption type
                        msg.encryptionType = StreamMessageEncryptionCode.spixi1;
                    }
                    else if (!friend.bot)
                    {
                        // upgrade encryption type
                        msg.encryptionType = StreamMessageEncryptionCode.rsa;
                    }
                }
                if (msg.encryptionType != StreamMessageEncryptionCode.none)
                {
                    if (msg.version == 0 && msg.encryptionType == StreamMessageEncryptionCode.rsa && !msg.encrypted)
                    {
                        msg.sign(IxianHandler.getWalletStorage().getPrimaryPrivateKey());
                    }
                    if (!msg.encrypt(friend.publicKey, friend.aesKey, friend.chachaKey))
                    {
                        Logging.warn("Could not encrypt message for {0}!", Base58Check.Base58CheckEncoding.EncodePlain(msg.recipient));
                        return(false);
                    }
                    if (msg.version > 0 && msg.encryptionType == StreamMessageEncryptionCode.rsa)
                    {
                        msg.sign(IxianHandler.getWalletStorage().getPrimaryPrivateKey());
                    }
                }
            }
            else if (msg.encryptionType != StreamMessageEncryptionCode.none)
            {
                if (friend.publicKey == null)
                {
                    byte[] pub_k = FriendList.findContactPubkey(friend.walletAddress);
                    friend.setPublicKey(pub_k);
                }
                if (!friend.bot)
                {
                    Logging.warn("Could not send message to {0}, due to missing encryption keys!", Base58Check.Base58CheckEncoding.EncodePlain(msg.recipient));
                    // Return true in case it has other messages in the queue that need to be processed and aren't encrypted
                    return(true);
                }
                else
                {
                    // TODO TODO TODO perhaps it would be better to discard such message and notify the user
                    Logging.warn("Tried sending encrypted message of type {0} without encryption keys to {1}, which is a bot, changing message encryption type to none!", msg.type, Base58Check.Base58CheckEncoding.EncodePlain(msg.recipient));
                    msg.encryptionType = StreamMessageEncryptionCode.none;
                }
            }

            bool   sent     = false;
            string hostname = friend.searchForRelay(); // TODO cuckoo filter should be used instead, need to check the performance when PL is big

            if (friend.online)
            {
                if (hostname != "" && hostname != null)
                {
                    StreamClientManager.connectTo(hostname, null); // TODO replace null with node address
                    sent = StreamClientManager.sendToClient(hostname, ProtocolMessageCode.s2data, msg.getBytes(), msg.id);
                    if (sent && pending_message.removeAfterSending)
                    {
                        removeMessage(friend, pending_message.streamMessage.id);
                    }
                }
            }

            if (friend.forcePush || !friend.online || !sent)
            {
                if (send_to_server)
                {
                    send_to_server = Config.enablePushNotifications;
                    if (friend.bot)
                    {
                        send_to_server         = false;
                        send_push_notification = false;
                    }
                }
                if (send_to_server)
                {
                    if (OfflinePushMessages.sendPushMessage(msg, send_push_notification))
                    {
                        pending_message.sendToServer = false;
                        if (add_to_pending_messages)
                        {
                            pending_message.save(storagePath);
                        }
                        PendingMessageHeader tmp_msg_header = getPendingMessageHeader(friend, pending_message.streamMessage.id);
                        if (tmp_msg_header != null)
                        {
                            tmp_msg_header.sendToServer = false;
                        }
                        if (pending_message.removeAfterSending)
                        {
                            removeMessage(friend, pending_message.streamMessage.id);
                        }
                        return(true);
                    }
                }
                return(false);
            }

            return(true);

            /*         string pub_k = FriendList.findContactPubkey(msg.recipientAddress);
             *       if (pub_k.Length < 1)
             *       {
             *           Console.WriteLine("Contact {0} not found, adding to offline queue!", msg.recipientAddress);
             *           addOfflineMessage(msg);
             *           return;
             *       }
             *
             *
             *       // Create a new IXIAN transaction
             *       //  byte[] checksum = Crypto.sha256(encrypted_message);
             *       Transaction transaction = new Transaction(0, msg.recipientAddress, Node.walletStorage.address);
             *       //  transaction.data = Encoding.UTF8.GetString(checksum);
             *       msg.transactionID = transaction.id;
             *       //ProtocolMessage.broadcastProtocolMessage(ProtocolMessageCode.newTransaction, transaction.getBytes());
             *
             *       // Add message to the queue
             *       messages.Add(msg);
             *
             *       // Request a new keypair from the S2 Node
             *       if(hostname == null)
             *           ProtocolMessage.broadcastProtocolMessage(ProtocolMessageCode.s2generateKeys, Encoding.UTF8.GetBytes(msg.getID()));
             *       else
             *       {
             *           NetworkClientManager.sendData(ProtocolMessageCode.s2generateKeys, Encoding.UTF8.GetBytes(msg.getID()), hostname);
             *       }*/
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Download profile pictures of the users
        /// </summary>
        /// <param name="friends">Friend list</param>
        /// <param name="dir">Destination directory</param>
        /// <param name="worker">To report progress</param>
        private static void DownloadPictures(FriendList friends, string dir, BackgroundWorker worker = null)
        {
            int i = 0;
            foreach(Friend f in friends) {
                if(worker != null && worker.CancellationPending)
                    throw new InterruptedException();

                if(File.Exists(dir + "/" + f.id + ".jpg")) {
                    if(worker != null)
                        worker.ReportProgress((++i * 100) / friends.Count, i);

                    continue;
                }

                string url = GraphAPI.GetData(f.id + "?fields=picture").SelectToken("picture")
                                                                       .SelectToken("data")
                                                                       .SelectToken("url")
                                                                       .ToString();
                DownloadFile(url, dir + "/" + f.id + ".jpg");

                if(worker != null)
                    worker.ReportProgress((++i * 100) / friends.Count, i);
            }
        }
Ejemplo n.º 8
0
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            var birthdayString = string.Format("{0}/{1}/{2}", model.Day, model.Month, model.Year);
            DateTime birthday;
            var parseResult = DateTime.TryParseExact(birthdayString, DateTimeFormat.DMYYYY, CultureInfo.InvariantCulture, DateTimeStyles.None,
                out birthday);

            if (parseResult && ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.UserName };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    var userInfo = new User
                    {
                        UserID = user.Id,
                        Email = model.Email,
                        FirstName = model.Firstname,
                        LastName = model.Lastname,
                        UserName = model.UserName,
                        BirthDay = birthday,
                        Gender = model.Gender,
                        Relationship = (int)Relationship.Single,
                        RegisteredDate = DateTime.UtcNow
                    };
                    db.Users.Add(userInfo);
                    db.SaveChanges(); 

                    var friendList = new FriendList
                    {
                        Id = user.Id,
                        UserId = user.Id,
                        CreatedDate = DateTime.UtcNow
                    };
                    db.FriendLists.Add(friendList);

                    var mySetting = new MySetting
                    {
                        SettingID = Guid.NewGuid().ToString(),
                        UserID = user.Id,
                        AllowOtherToPost = true,
                        DefaultMyPostVisibility = (int)VisibleType.Friend,
                        DefaultOtherPostVisibility = (int)VisibleType.Friend,
                        ShowBirthday = (int)ShowBirthDay.Show
                    };
                    db.MySettings.Add(mySetting);

                    //Init default album avatar and cover
                    db.Albums.AddRange(DefaultAlbum(user.Id));
                    //Init default image
                    db.AlbumDetails.AddRange(DefaultImage(user.Id, userInfo.Gender));

                    db.SaveChanges();

                    await SignInAsync(user, isPersistent: false);
                    return RedirectToAction("Newsfeed", "Home");
                }
                else
                {
                    AddErrors(result);
                }
            }
            else
            {
                ModelState.AddModelError("", Message.INVALID_BIRTHDAY);
            }


            // If we got this far, something failed, redisplay form
            return View(model);
        }
Ejemplo n.º 9
0
        public MainWindow()
        {
            PerMsg  p1 = new PerMsg("wang", "ceshi");
            PerMsg  p2 = new PerMsg("wang", "ceshi");
            PerMsg  p3 = new PerMsg("wang", "ceshi");
            MsgList m1 = new MsgList();

            m1.Add(p1);
            m1.Add(p2);
            m1.Add(p3);

            PerMsg  p4 = new PerMsg("ming", "ceshi");
            PerMsg  p5 = new PerMsg("ming", "ceshi");
            PerMsg  p6 = new PerMsg("ming", "ceshi");
            MsgList m2 = new MsgList();

            m2.Add(p4);
            m2.Add(p5);
            m2.Add(p6);

            PerMsg  p7 = new PerMsg("gao", "ceshi");
            PerMsg  p8 = new PerMsg("gao", "ceshi");
            PerMsg  p9 = new PerMsg("gao", "ceshi");
            MsgList m3 = new MsgList();

            m3.Add(p7);
            m3.Add(p8);
            m3.Add(p9);


            friends = new FriendList
            {
                new Friend {
                    UserId = "1234", UserName = "******", IP = "192.168.1.1", status = Status.Online
                },
                new Friend {
                    UserId = "2345", UserName = "******", IP = "192,168.1.2", status = Status.Online
                },
                new Friend {
                    UserId = "3456", UserName = "******", IP = "192.168.1.3", status = Status.Offline
                }
            };

            chats = new ChatList
            {
                //new Chat{SenderId = "1234", sName="wang", ReceiverId = "1111", Content = "测试测试测试测试测试测试", Msgs = m1, WaitReads = 3},
                //new Chat{SenderId = "2345", sName="ming", ReceiverId = "1111", Content = "测试测试测试测试测试", Msgs = m2,WaitReads = 3},
                //new Chat{SenderId = "3456", sName="gao", ReceiverId = "1111", Content= "测试测试测试测试", Msgs = m3,WaitReads = 3}
                new Chat("1234", "wang", "1111", "测试测试测试测试测试测试", m1, 0),
                new Chat("2345", "ming", "1111", "测试测试测试测试测试", m2, 0),
                new Chat("3456", "gao", "1111", "测试测试测试测试", m3, 0),
            };
            notices = new NoticeList
            {
                new Notice {
                    UserId = "5678"
                },
                new Notice {
                    UserId = "4567"
                }
            };
            model = new ChatViewModel {
                AllChatWaitReads = 0, AllFriendWaitReads = 0, AllNoticeWaitReads = 0
            };

            InitializeComponent();
            this.tabMain.DataContext = model;
            this.gChat.DataContext   = chats;
            this.gFriend.DataContext = friends;
            this.gNotice.DataContext = notices;

            this.listChat.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(listChat_MouseLeftButtonDown), true);
            this.listChat.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(listChat_MouseRightButtonDown), true);
        }
Ejemplo n.º 10
0
        public void ProcessRequest()
        {
            AuthUser my = My;
            int      friendGroupID;
            bool     useDefault = _Request.Get("default", Method.Get, "").ToLower() == "true";

            if (useDefault)
            {
                friendGroupID = my.SelectFriendGroupID;
            }
            else
            {
                friendGroupID = _Request.Get <int>("groupid", Method.Get, -1);
            }

            if (my.SelectFriendGroupID != friendGroupID)
            {
                my.SelectFriendGroupID = friendGroupID;
                try
                {
                    UserBO.Instance.UpdateUserSelectFriendGroupID(my, friendGroupID);
                }
                catch (Exception ex)
                {
                    LogHelper.CreateErrorLog(ex);
                }
            }

            List <int>       currentGroupUserIDs = new List <int>();
            FriendCollection friends             = FriendBO.Instance.GetFriends(my.UserID);

            Dictionary <int, int> onlineCount = new Dictionary <int, int>();

            foreach (Friend friend in friends)
            {
                if (friend.GroupID == friendGroupID)
                {
                    currentGroupUserIDs.Add(friend.UserID);
                    if (friend.GroupID == my.SelectFriendGroupID)
                    {
                        FriendList.Add(friend);
                    }
                }

#if !Passport
                if (friend.IsOnline)
                {
                    if (onlineCount.ContainsKey(friend.GroupID))
                    {
                        onlineCount[friend.GroupID] += 1;
                    }
                    else
                    {
                        onlineCount.Add(friend.GroupID, 1);
                    }
                }
#endif
            }

            foreach (FriendGroup group in my.FriendGroups)
            {
                int count;
                if (
                    onlineCount.TryGetValue(group.GroupID, out count))
                {
                    group.OnlineCount = count;
                }
                group.IsSelect = group.GroupID == my.SelectFriendGroupID;
            }

            UserBO.Instance.FillSimpleUsers <Friend>(this.FriendList);

            //SimpleUserCollection users = UserBO.Instance.GetSimpleUsers(currentGroupUserIDs, GetUserOption.Default);
        }
Ejemplo n.º 11
0
		public static void Load()
		{
			string idxPath = Path.Combine( "Saves/FriendLists", "FriendLists.idx" );
			string binPath = Path.Combine( "Saves/FriendLists", "FriendLists.bin" );

			if (File.Exists(idxPath) && File.Exists(binPath))
			{
				// Declare and initialize reader objects.
				FileStream idx = new FileStream(idxPath, FileMode.Open, FileAccess.Read, FileShare.Read);
				FileStream bin = new FileStream(binPath, FileMode.Open, FileAccess.Read, FileShare.Read);
				BinaryReader idxReader = new BinaryReader(idx);
				BinaryFileReader binReader = new BinaryFileReader(new BinaryReader(bin));

				// Start by reading the number of duels from an index file
				int orderCount = idxReader.ReadInt32();

				for (int i = 0; i < orderCount; ++i)
				{

					FriendList fl = new FriendList();
					// Read start-position and length of current order from index file
					long startPos = idxReader.ReadInt64();
					int length = idxReader.ReadInt32();
					// Point the reading stream to the proper position
					binReader.Seek(startPos, SeekOrigin.Begin);

					try
					{
						fl.Deserialize(binReader);

						if (binReader.Position != (startPos + length))
							throw new Exception(String.Format("***** Bad serialize on FriendList[{0}] *****", i));
					}
					catch
					{
						//handle
					}
					if ( fl != null && fl.m_Mobile != null )
						FriendLists.Add( fl.m_Mobile, fl );
				}
				// Remember to close the streams
				idxReader.Close();
				binReader.Close();
			}

		}
Ejemplo n.º 12
0
 /// <summary>
 /// Checks if a specified user belongs to the friend list.
 /// </summary>
 /// <param name="name">The name of the user.</param>
 public bool IsFriend(string name)
 {
     return(FriendList.Contains(name));
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Loads all mutual friends of all friends and saves them into a graph
        /// </summary>
        public void LoadConnections(FriendList fl, BackgroundWorker worker = null)
        {
            data = new FriendGraph();
            friends = new Dictionary<string, Friend>();

            // creates id->friend addresser
            foreach(Friend f in fl) {
                friends.Add(f.id, f);
                data.Add(f, new List<Friend>());
            }

            // downloades mutual friends of every friend in the list
            int i = 0;
            foreach(KeyValuePair<string, Friend> pair in friends) {
                if(worker != null && worker.CancellationPending)
                    throw new InterruptedException();

                FriendList mutualFriends = GraphAPI.GetData<FriendList>(pair.Key + "/mutualfriends");

                foreach(Friend f in mutualFriends) {
                    if(!data[pair.Value].Contains(f))
                        data[pair.Value].Add(f);
                }

                // reporting progress
                if(worker != null)
                    worker.ReportProgress((++i * 100) / friends.Count, i);
            }
        }
Ejemplo n.º 14
0
 private void ExecuteRemoveFriend()
 {
     FriendList.Remove(objItemSelected);
     objItemSelected = null;
 }
Ejemplo n.º 15
0
 public FriendList updatefriendlist()
 {
     friend = Action.getFriendlist();
     return(friend);
 }
Ejemplo n.º 16
0
 public FriendList searchfriend(string name)
 {
     friend = Action.searchfriend(name);
     return(friend);
 }
Ejemplo n.º 17
0
 public FriendList updateApprovefriendlist()
 {
     friend = Action.getApproveFriendlist();
     return(friend);
 }
 public async Task <FriendList> RequestFriend(FriendList newF)
 {
     return(await _repository.RequestFriend(newF));
 }
Ejemplo n.º 19
0
        public async Task <Bill> InsertBillAsync(BillModel bill)
        {
            Bill newBill = new Bill();

            newBill.BillName    = bill.BillName;
            newBill.CreatorId   = bill.CreatorId;
            newBill.Amount      = bill.Amount;
            newBill.CreatedDate = bill.CreatedDate;
            newBill.GroupId     = bill.GroupId;
            _Context.Bill.Add(newBill);


            foreach (var person in bill.Payer)
            {
                Payer payer = new Payer();
                payer.BillId     = newBill.BillId;
                payer.PayerId    = person.Id;
                payer.PaidAmount = person.Amount;
                _Context.Payer.Add(payer);
            }


            foreach (var person in bill.SharedMember)
            {
                BillMember member = new BillMember();
                member.Billid         = newBill.BillId;
                member.SharedMemberId = person.Id;
                member.AmountToPay    = person.Amount;
                _Context.BillMember.Add(member);
            }


            for (var i = 0; i < bill.SharedMember.Count - 1; i++)
            {
                for (var j = i + 1; j < bill.SharedMember.Count; j++)
                {
                    var fExist = _Context.FriendList.SingleOrDefault(c => c.UserId == bill.SharedMember[i].Id && c.FriendId == bill.SharedMember[j].Id);
                    if (fExist == null)
                    {
                        var Exist = _Context.FriendList.SingleOrDefault(c => c.UserId == bill.SharedMember[j].Id && c.FriendId == bill.SharedMember[i].Id);
                        if (Exist == null)
                        {
                            FriendList newFriend = new FriendList
                            {
                                UserId   = bill.SharedMember[i].Id,
                                FriendId = bill.SharedMember[j].Id
                            };
                            _Context.FriendList.Add(newFriend);
                            await _Context.SaveChangesAsync();
                        }
                    }
                }
            }


            foreach (var data in bill.SettleModels)
            {
                if (data.GroupId == null)
                {
                    var settle = await _Context.Settlement.SingleOrDefaultAsync(c => c.PayerId == data.PayerId && c.SharedMemberId == data.SharedMemberId && c.GroupId == null);

                    if (settle != null)
                    {
                        settle.TotalAmount = settle.TotalAmount + data.TotalAmount;
                        _Context.Settlement.Attach(settle);
                    }
                    else
                    {
                        var setle = await _Context.Settlement.SingleOrDefaultAsync(c => c.PayerId == data.SharedMemberId && c.SharedMemberId == data.PayerId && c.GroupId == null);

                        if (setle != null)
                        {
                            setle.TotalAmount = setle.TotalAmount - data.TotalAmount;
                            _Context.Settlement.Attach(setle);
                        }
                        else
                        {
                            var newSettle = new Settlement();
                            newSettle.PayerId        = data.PayerId;
                            newSettle.SharedMemberId = data.SharedMemberId;
                            newSettle.TotalAmount    = data.TotalAmount;
                            _Context.Settlement.Add(newSettle);
                        }
                    }
                }
                else
                {
                    var settle = await _Context.Settlement.SingleOrDefaultAsync(c => c.PayerId == data.PayerId && c.SharedMemberId == data.SharedMemberId && c.GroupId == data.GroupId);

                    if (settle != null)
                    {
                        settle.TotalAmount = settle.TotalAmount + data.TotalAmount;
                        _Context.Settlement.Attach(settle);
                    }
                    else
                    {
                        var setle = await _Context.Settlement.SingleOrDefaultAsync(c => c.PayerId == data.SharedMemberId && c.SharedMemberId == data.PayerId && c.GroupId == data.GroupId);

                        if (setle != null)
                        {
                            setle.TotalAmount = setle.TotalAmount - data.TotalAmount;
                            _Context.Settlement.Attach(setle);
                        }
                        else
                        {
                            var newSettle = new Settlement();
                            newSettle.PayerId        = data.PayerId;
                            newSettle.SharedMemberId = data.SharedMemberId;
                            newSettle.TotalAmount    = data.TotalAmount;
                            newSettle.GroupId        = data.GroupId;
                            _Context.Settlement.Add(newSettle);
                        }
                    }
                }
            }
            //if (newBill.GroupId == null)
            //{
            //    foreach (var person in bill.Payer)
            //    {
            //        foreach (var member in bill.SharedMember)
            //        {
            //            if (person.Id != member.Id)
            //            {
            //                Settlement settlement = new Settlement();
            //                settlement.PayerId = member.Id;
            //                settlement.SharedMemberId = person.Id;
            //                settlement.TotalAmount = member.Amount;

            //                var settle = await _Context.Settlement.SingleOrDefaultAsync(c => c.PayerId == settlement.PayerId && c.SharedMemberId == settlement.SharedMemberId && c.GroupId==null);
            //                if (settle != null)
            //                {
            //                    settle.TotalAmount = settle.TotalAmount + settlement.TotalAmount;
            //                    _Context.Settlement.Attach(settle);
            //                }
            //                else
            //                {
            //                    var setle = await _Context.Settlement.SingleOrDefaultAsync(c => c.PayerId == settlement.SharedMemberId && c.SharedMemberId == settlement.PayerId && c.GroupId == null);
            //                    if (setle != null)
            //                    {
            //                        setle.TotalAmount = setle.TotalAmount - settlement.TotalAmount;
            //                        _Context.Settlement.Attach(setle);
            //                    }
            //                    else
            //                    {
            //                        _Context.Settlement.Add(settlement);
            //                    }
            //                }

            //            }
            //        }
            //    }
            //}
            //else
            //{
            //    foreach (var person in bill.Payer)
            //    {
            //        foreach (var member in bill.SharedMember)
            //        {
            //            if (person.Id != member.Id)
            //            {
            //                Settlement settlement = new Settlement();
            //                settlement.GroupId = newBill.GroupId;
            //                settlement.PayerId = member.Id;
            //                settlement.SharedMemberId = person.Id;
            //                settlement.TotalAmount = member.Amount;

            //                var settle = await _Context.Settlement.SingleOrDefaultAsync(c => c.PayerId == settlement.PayerId && c.SharedMemberId == settlement.SharedMemberId && c.GroupId == settlement.GroupId);
            //                if (settle != null)
            //                {
            //                    settle.TotalAmount = settle.TotalAmount + settlement.TotalAmount;
            //                    _Context.Settlement.Attach(settle);
            //                }
            //                else
            //                {
            //                    var setle = await _Context.Settlement.SingleOrDefaultAsync(c => c.PayerId == settlement.SharedMemberId && c.SharedMemberId == settlement.PayerId && c.GroupId == settlement.GroupId);
            //                    if (setle != null)
            //                    {
            //                        setle.TotalAmount = setle.TotalAmount - settlement.TotalAmount;
            //                        _Context.Settlement.Attach(setle);
            //                    }
            //                    else
            //                    {
            //                        _Context.Settlement.Add(settlement);
            //                    }
            //                }
            //            }
            //        }
            //    }

            //}
            try
            {
                await _Context.SaveChangesAsync();
            }
            catch (System.Exception exp)
            {
                _Logger.LogError($"Error in {nameof(InsertBillAsync)}: " + exp.Message);
            }

            return(newBill);
        }
        private void Receive()
        {
            bool already_check = true;

            while (connected)
            {
                try
                {
                    Byte[] buffer = new Byte[128];
                    clientSocket.Receive(buffer);

                    string incomingMessage = Encoding.Default.GetString(buffer);
                    incomingMessage = incomingMessage.Substring(0, incomingMessage.IndexOf("\0"));
                    //logs.AppendText("Message received" + "\n");
                    //logs.AppendText("Server: " + incomingMessage + "\n");
                    if (incomingMessage == "EfeYarenYigitKayaYou successfully logged inEfeYarenYigitKaya")
                    {
                        textBox_message.Enabled = true;   //after successfully connection, textbox button should be active.
                        send_button.Enabled     = true;   //after connection, send button should be active.
                        logs.AppendText("Connected to the server!\n");
                        disconnect_button.Enabled = true; //after connected disconnect button should be active.
                        userName = incomingName;
                        connect_button.Enabled = false;   //already connected so connect button shoul be inactive
                        AcceptBut.Enabled      = true;
                        RejectBut.Enabled      = true;
                        friendsBut.Enabled     = true;
                        sendReqBut.Enabled     = true;
                        button1.Enabled        = true;
                        deleteButton.Enabled   = true;
                    }
                    else if (incomingMessage == "EfeYarenYigitKayaThis username does not exist in databaseEfeYarenYigitKaya") //server sends does not exist message
                    {
                        logs.AppendText("You are not in the database\n");                                                     //if this message came from the server and username was wrong, print this
                    }
                    else if (incomingMessage == "EfeYarenYigitKayaYou are already logged inEfeYarenYigitKaya")
                    {
                        logs.AppendText("You already logged in\n"); //correct username but it already connected
                        already_check = false;                      //for blocked to another connection from same user
                    }
                    else if (incomingMessage.Length > 18 && incomingMessage.Substring(0, 18) == "EfeYarenYigitKaya£")
                    {
                        string inviter = incomingMessage.Substring(18, incomingMessage.Length - 18);
                        if (!requestList.Contains(inviter))
                        {
                            requestList.Add(inviter); // yeni ekledim whenever you receive request that does not exist in your request list add it to your list
                        }
                        friendReqList.Clear();
                        //requestList.Add(inviter);
                        //bool flag = true;
                        string currentRequest = "";
                        foreach (string name in requestList)
                        {
                            currentRequest += name + "\n";
                        }
                        friendReqList.AppendText(currentRequest);
                        //    if(name == inviter)
                        //    {
                        //        flag = false;
                        //    }
                        //}
                        //if (flag)
                        //{
                        //    requestList.Add(inviter);
                        //    currentRequest += inviter;
                        //}
                        //friendReqList.AppendText(currentRequest + "\n");
                        //friendReqList.AppendText(inviter + "\n");
                    }
                    else if (incomingMessage.Length > 18 && incomingMessage.Substring(0, 19) == "EfeYarenYigitKaya*£")
                    {
                        string myMessage = incomingMessage.Substring(19, incomingMessage.Length - 19);
                        logs.AppendText(myMessage + "\n");
                    }
                    else if (incomingMessage.Length > 18 && incomingMessage.Substring(0, 19) == "EfeYarenYigitKaya*!")
                    {
                        int    index     = incomingMessage.IndexOf("%");
                        string sender    = incomingMessage.Substring(19, index - 19);
                        string myMessage = incomingMessage.Substring(index + 1);
                        logs.AppendText(sender + ": " + myMessage + "\n");
                    }
                    else if (incomingMessage.Length > 18 && incomingMessage.Substring(0, 20) == "EfeYarenYigitKaya*<f")
                    {
                        string deletedfriend = incomingMessage.Substring(20);
                        logs.AppendText("There is no such friend as " + deletedfriend + " in your friends list\n");
                    }
                    else if (incomingMessage.Length > 18 && incomingMessage.Substring(0, 20) == "EfeYarenYigitKaya*<s")
                    {
                        string deletedfriend = incomingMessage.Substring(20);
                        logs.AppendText("You have succesfully remove " + deletedfriend + " from your friends list\n");
                    }
                    else if (incomingMessage.Length > 18 && incomingMessage.Substring(0, 19) == "EfeYarenYigitKaya*<")
                    {
                        string clientName = incomingMessage.Substring(19);
                        logs.AppendText(clientName + " removed you from friends\n");
                    }

                    else if (incomingMessage.Length > 18 && incomingMessage.Substring(0, 18) == "EfeYarenYigitKaya#") // once accept friend request
                    {
                        string invitee = incomingMessage.Substring(18, incomingMessage.Length - 18);
                        //friendReqList.AppendText(invitee + "\n");
                        logs.AppendText(invitee + " Accepted your friend request\n");
                    }
                    else if (incomingMessage.Length > 18 && incomingMessage.Substring(0, 18) == "EfeYarenYigitKaya&")
                    {
                        string invitee = incomingMessage.Substring(18, incomingMessage.Length - 18);
                        friendReqList.AppendText(invitee + "\n");
                    }
                    else if (incomingMessage.Length > 18 && incomingMessage.Substring(0, 19) == "EfeYarenYigitKaya*&")
                    {
                        string invitee = incomingMessage.Substring(19, incomingMessage.Length - 19);
                        logs.AppendText(invitee + "\n");
                    }

                    else if (incomingMessage.Length > 17 && incomingMessage.Substring(0, 18) == "EfeYarenYigitKaya$") // receive friends from server
                    {
                        //FriendList.AppendText("print friend list");
                        FriendList.Clear();
                        string friends = incomingMessage.Substring(18, incomingMessage.Length - 18);
                        friends = friends.Replace(',', '\n');
                        FriendList.AppendText(friends);
                        //if(friends.Length > 1)
                        //FriendList.AppendText("********\n");
                    }
                    else if (incomingMessage.Substring(0, 3) == "123")
                    {
                        logs.AppendText(incomingMessage.Substring(3)); // you have already requested and wait for answer
                    }
                    else if (incomingMessage.Substring(0, 3) == "321")
                    {
                        logs.AppendText(incomingMessage.Substring(3)); // you requested but there is no such user in database
                    }
                    else
                    {
                        incomingMessage = incomingMessage.Substring(17, incomingMessage.Length - 34); //true connection and message
                        logs.AppendText(incomingMessage + "\n");                                      //print the incoming message
                    }
                }
                catch (Exception e)
                {
                    //FriendList.AppendText(e.Message);
                    if (!terminating)
                    {
                        if (already_check)
                        {
                            logs.AppendText("The server has disconnected\n"); //disconnect button activated
                        }
                        server_check            = false;
                        already_check           = true;  // user can enter again
                        connect_button.Enabled  = true;  //user can connect again because disconnect now
                        textBox_message.Enabled = false; //user cannot write text
                        send_button.Enabled     = false; //user cannot send message
                    }

                    clientSocket.Close();
                    connected = false;
                }
            }
        }
 /// <summary>
 /// 获取关注好友列表
 /// </summary>
 /// <returns></returns>
 protected string WeiboUser_friend()
 {
     int user_id = 0;
     var _IsOk = false;
     var _ErrorMessage = "";
     int _next_cursor = 0;
     List<FriendList> lfl = new List<FriendList>();
     var data = new
     {
         friList = lfl,
         IsOk = _IsOk,
         ErrorMessage = _ErrorMessage
     };
     user_id = Convert.ToInt32(Session["userid"]);    //? user_id : Convert.ToInt32(Session["userid"]);
     if (user_id != 0)
     {
         string sina_id = cdc.E_Card2012_UserInfo.Single(ui => ui.Id == user_id).SinaId;
         var dto = Wbm.SinaV2API.SinaControllers.UserController.GetFriendList(Convert.ToInt64(sina_id));  //获取关注人列表
         _next_cursor = dto.next_cursor;
         if (dto.users != null)
         {
             int page = (dto.total_number / 50) + ((dto.total_number % 50) > 0 ? 1 : 0); //  dto.total_number / 50;
             for (int i = 0; i <= page; i++)
             {
                 var dt = Wbm.SinaV2API.SinaControllers.UserController.GetFriendList(Convert.ToInt64(sina_id), _next_cursor);
                 _next_cursor = dt.next_cursor;
                 if (dt.users.Count() == 0)
                 {
                 }
                 else
                 {
                     foreach (var item in dt.users)
                     {
                         FriendList fl = new FriendList();
                         fl.id = item.id.ToString();
                         fl.name = item.name.Length > 7 ? item.name.Substring(0, 7) + "..." : item.name;
                         fl.image_url = item.profile_image_url;
                         lfl.Add(fl);
                     }
                 }
             }
             _IsOk = true;
         }
         else
         {
             _IsOk = false;
             _ErrorMessage = "亲~你凹凸曼了 新注册的微博吧!";
         }
     }
     else
     {
         _IsOk = false;
         _ErrorMessage = "你没有登陆!请登录获得更多的体验哦!";
     }
     data = new
     {
         friList = lfl,
         IsOk = _IsOk,
         ErrorMessage = _ErrorMessage
     };
     return JavaScriptConvert.SerializeObject(data);
 }
Ejemplo n.º 22
0
		public static FriendList GetFriendList( Mobile m )
		{
			if ( m == null )
				return null;
			FriendList fl = (FriendList)FriendLists[m];
			if ( fl == null )
			{
				fl = new FriendList( m );
				FriendLists.Add( m, fl );
			}
			return fl;
		}
        /// <summary>
        /// 根据关键字查找关注好友
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        protected string WeiboUser_Selfriend(string key)
        {
            var _IsOk = false;
            var _ErrorMessage = "";
            var weibo_username = "";
            int next_cursor = 0;
            List<FriendList> lfl = new List<FriendList>();
            var data = new
            {
                friList = lfl,
                IsOk = _IsOk,
                ErrorMessage = _ErrorMessage
            };
            if (Session["username"] != null)
                weibo_username = Session["username"].ToString();
            else
                weibo_username = "";
            if (weibo_username != "")
            {
                string sina_id = cdc.E_Card2012_UserInfo.Single(ui => ui.NikeName == weibo_username).SinaId;
                var dto = Wbm.SinaV2API.SinaControllers.UserController.GetFriendList(Convert.ToInt64(sina_id));  //获取关注人列表
                next_cursor = dto.next_cursor;
                if (dto != null)
                {
                    int page = (dto.total_number / 50) + ((dto.total_number % 50) > 0 ? 1 : 0); //  dto.total_number / 50;
                    for (int i = 1; i <= page; i++)
                    {
                        var dt = Wbm.SinaV2API.SinaControllers.UserController.GetFriendList(Convert.ToInt64(sina_id), next_cursor);
                        next_cursor = dt.next_cursor;
                        var dd = dt.users.Where(a => a.screen_name.Contains(key))
                          .Select(a => new { a.id, a.name, a.profile_image_url });
                        //.Take(PageSize)
                        if (dd.Count() == 0)
                        {
                        }
                        else
                        {
                            foreach (var item in dd)
                            {
                                FriendList fl = new FriendList();
                                fl.id = item.id.ToString();
                                fl.name = item.name.Length > 7 ? item.name.Substring(0, 7) + "..." : item.name;
                                fl.image_url = item.profile_image_url;
                                lfl.Add(fl);
                            }
                        }
                    }

                    if (lfl.Count == 0 || lfl == null)
                    {
                        _ErrorMessage = "没有相关内容的朋友!";
                    }
                    _IsOk = true;
                }
                else
                {
                    _IsOk = false;
                    _ErrorMessage = "亲~你凹凸曼了 新注册的微博吧!";
                }
            }
            else
            {
                _IsOk = false;
                _ErrorMessage = "你未登录,请登录在使用!";
            }
            data = new
            {
                friList = lfl,
                IsOk = _IsOk,
                ErrorMessage = _ErrorMessage
            };
            return JavaScriptConvert.SerializeObject(data);
        }
Ejemplo n.º 24
0
 internal Player()
 {
     Account    = new Account();
     Abilities  = new Abilities();
     FriendList = new FriendList();
 }
 public async Task FriendRequest(FriendList fl)
 {
     FriendList newf = new FriendList(fl.FriendId, fl.RequestedFriendId, fl.ToUsername, fl.FromUsername);
     await _businessLogicClass.RequestFriend(newf);
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Checks if a specified user belongs to the friend list.
 /// </summary>
 /// <param name="name">The name of the user.</param>
 public bool IsFriend(string name) => FriendList.Contains(name);
 public async Task AcceptFriend(FriendList friend)
 {
     await _businessLogicClass.AcceptFriend(friend);
 }
Ejemplo n.º 28
0
        // Unified protocol message parsing
        public static void parseProtocolMessage(ProtocolMessageCode code, byte[] data, RemoteEndpoint endpoint)
        {
            if (endpoint == null)
            {
                Logging.error("Endpoint was null. parseProtocolMessage");
                return;
            }
            try
            {
                switch (code)
                {
                case ProtocolMessageCode.hello:
                {
                    using (MemoryStream m = new MemoryStream(data))
                    {
                        using (BinaryReader reader = new BinaryReader(m))
                        {
                            CoreProtocolMessage.processHelloMessageV6(endpoint, reader);
                        }
                    }
                }
                break;


                case ProtocolMessageCode.helloData:
                    using (MemoryStream m = new MemoryStream(data))
                    {
                        using (BinaryReader reader = new BinaryReader(m))
                        {
                            if (!CoreProtocolMessage.processHelloMessageV6(endpoint, reader))
                            {
                                return;
                            }

                            ulong  last_block_num = reader.ReadIxiVarUInt();
                            int    bcLen          = (int)reader.ReadIxiVarUInt();
                            byte[] block_checksum = reader.ReadBytes(bcLen);

                            endpoint.blockHeight = last_block_num;

                            int block_version = (int)reader.ReadIxiVarUInt();

                            if (endpoint.presenceAddress.type != 'C')
                            {
                                ulong highest_block_height = IxianHandler.getHighestKnownNetworkBlockHeight();
                                if (last_block_num + 10 < highest_block_height)
                                {
                                    CoreProtocolMessage.sendBye(endpoint, ProtocolByeCode.tooFarBehind, string.Format("Your node is too far behind, your block height is {0}, highest network block height is {1}.", last_block_num, highest_block_height), highest_block_height.ToString(), true);
                                    return;
                                }
                            }

                            // Process the hello data
                            endpoint.helloReceived = true;
                            NetworkClientManager.recalculateLocalTimeDifference();

                            if (endpoint.presenceAddress.type == 'R')
                            {
                                string[] connected_servers = StreamClientManager.getConnectedClients(true);
                                if (connected_servers.Count() == 1 || !connected_servers.Contains(StreamClientManager.primaryS2Address))
                                {
                                    if (StreamClientManager.primaryS2Address == "")
                                    {
                                        FriendList.requestAllFriendsPresences();
                                    }
                                    // TODO set the primary s2 host more efficiently, perhaps allow for multiple s2 primary hosts
                                    StreamClientManager.primaryS2Address = endpoint.getFullAddress(true);
                                    // TODO TODO do not set if directly connectable
                                    IxianHandler.publicIP           = endpoint.address;
                                    IxianHandler.publicPort         = endpoint.incomingPort;
                                    PresenceList.forceSendKeepAlive = true;
                                    Logging.info("Forcing KA from networkprotocol");
                                }
                            }
                            else if (endpoint.presenceAddress.type == 'C')
                            {
                                Friend f = FriendList.getFriend(endpoint.presence.wallet);
                                if (f != null && f.bot)
                                {
                                    StreamProcessor.sendGetBotInfo(f);
                                }
                            }

                            if (endpoint.presenceAddress.type == 'M' || endpoint.presenceAddress.type == 'H')
                            {
                                Node.setNetworkBlock(last_block_num, block_checksum, block_version);

                                // Get random presences
                                endpoint.sendData(ProtocolMessageCode.getRandomPresences, new byte[1] {
                                    (byte)'R'
                                });
                                endpoint.sendData(ProtocolMessageCode.getRandomPresences, new byte[1] {
                                    (byte)'M'
                                });
                                endpoint.sendData(ProtocolMessageCode.getRandomPresences, new byte[1] {
                                    (byte)'H'
                                });

                                subscribeToEvents(endpoint);
                            }
                        }
                    }
                    break;

                case ProtocolMessageCode.s2data:
                {
                    StreamProcessor.receiveData(data, endpoint);
                }
                break;

                case ProtocolMessageCode.updatePresence:
                {
                    Logging.info("NET: Receiving presence list update");
                    // Parse the data and update entries in the presence list
                    Presence p = PresenceList.updateFromBytes(data);
                    if (p == null)
                    {
                        return;
                    }

                    Friend f = FriendList.getFriend(p.wallet);
                    if (f != null)
                    {
                        f.relayIP = p.addresses[0].address;
                    }
                }
                break;

                case ProtocolMessageCode.keepAlivePresence:
                {
                    byte[]   address   = null;
                    long     last_seen = 0;
                    byte[]   device_id = null;
                    bool     updated   = PresenceList.receiveKeepAlive(data, out address, out last_seen, out device_id, endpoint);
                    Presence p         = PresenceList.getPresenceByAddress(address);
                    if (p == null)
                    {
                        return;
                    }

                    Friend f = FriendList.getFriend(p.wallet);
                    if (f != null)
                    {
                        f.relayIP = p.addresses[0].address;
                    }
                }
                break;

                case ProtocolMessageCode.getPresence:
                {
                    using (MemoryStream m = new MemoryStream(data))
                    {
                        using (BinaryReader reader = new BinaryReader(m))
                        {
                            int    walletLen = reader.ReadInt32();
                            byte[] wallet    = reader.ReadBytes(walletLen);

                            Presence p = PresenceList.getPresenceByAddress(wallet);
                            if (p != null)
                            {
                                lock (p)
                                {
                                    byte[][] presence_chunks = p.getByteChunks();
                                    foreach (byte[] presence_chunk in presence_chunks)
                                    {
                                        endpoint.sendData(ProtocolMessageCode.updatePresence, presence_chunk, null);
                                    }
                                }
                            }
                            else
                            {
                                // TODO blacklisting point
                                Logging.warn(string.Format("Node has requested presence information about {0} that is not in our PL.", Base58Check.Base58CheckEncoding.EncodePlain(wallet)));
                            }
                        }
                    }
                }
                break;

                case ProtocolMessageCode.getPresence2:
                {
                    using (MemoryStream m = new MemoryStream(data))
                    {
                        using (BinaryReader reader = new BinaryReader(m))
                        {
                            int    walletLen = (int)reader.ReadIxiVarUInt();
                            byte[] wallet    = reader.ReadBytes(walletLen);

                            Presence p = PresenceList.getPresenceByAddress(wallet);
                            if (p != null)
                            {
                                lock (p)
                                {
                                    byte[][] presence_chunks = p.getByteChunks();
                                    foreach (byte[] presence_chunk in presence_chunks)
                                    {
                                        endpoint.sendData(ProtocolMessageCode.updatePresence, presence_chunk, null);
                                    }
                                }
                            }
                            else
                            {
                                // TODO blacklisting point
                                Logging.warn(string.Format("Node has requested presence information about {0} that is not in our PL.", Base58Check.Base58CheckEncoding.EncodePlain(wallet)));
                            }
                        }
                    }
                }
                break;

                case ProtocolMessageCode.balance:
                {
                    using (MemoryStream m = new MemoryStream(data))
                    {
                        using (BinaryReader reader = new BinaryReader(m))
                        {
                            int    address_length = reader.ReadInt32();
                            byte[] address        = reader.ReadBytes(address_length);

                            // Retrieve the latest balance
                            IxiNumber balance = reader.ReadString();

                            if (address.SequenceEqual(Node.walletStorage.getPrimaryAddress()))
                            {
                                // Retrieve the blockheight for the balance
                                ulong block_height = reader.ReadUInt64();

                                if (block_height > Node.balance.blockHeight && (Node.balance.balance != balance || Node.balance.blockHeight == 0))
                                {
                                    byte[] block_checksum = reader.ReadBytes(reader.ReadInt32());

                                    Node.balance.address       = address;
                                    Node.balance.balance       = balance;
                                    Node.balance.blockHeight   = block_height;
                                    Node.balance.blockChecksum = block_checksum;
                                    Node.balance.verified      = false;
                                }
                                Node.balance.lastUpdate = Clock.getTimestamp();
                            }
                        }
                    }
                }
                break;

                case ProtocolMessageCode.balance2:
                {
                    using (MemoryStream m = new MemoryStream(data))
                    {
                        using (BinaryReader reader = new BinaryReader(m))
                        {
                            int    address_length = (int)reader.ReadIxiVarUInt();
                            byte[] address        = reader.ReadBytes(address_length);

                            // Retrieve the latest balance
                            IxiNumber balance = new IxiNumber(new BigInteger(reader.ReadBytes((int)reader.ReadIxiVarUInt())));

                            if (address.SequenceEqual(Node.walletStorage.getPrimaryAddress()))
                            {
                                // Retrieve the blockheight for the balance
                                ulong block_height = reader.ReadIxiVarUInt();

                                if (block_height > Node.balance.blockHeight && (Node.balance.balance != balance || Node.balance.blockHeight == 0))
                                {
                                    byte[] block_checksum = reader.ReadBytes((int)reader.ReadIxiVarUInt());

                                    Node.balance.address       = address;
                                    Node.balance.balance       = balance;
                                    Node.balance.blockHeight   = block_height;
                                    Node.balance.blockChecksum = block_checksum;
                                    Node.balance.verified      = false;
                                }
                                Node.balance.lastUpdate = Clock.getTimestamp();
                            }
                        }
                    }
                }
                break;

                case ProtocolMessageCode.newTransaction:
                case ProtocolMessageCode.transactionData:
                {
                    // TODO: check for errors/exceptions
                    Transaction transaction = new Transaction(data, true);

                    if (endpoint.presenceAddress.type == 'M' || endpoint.presenceAddress.type == 'H')
                    {
                        PendingTransactions.increaseReceivedCount(transaction.id, endpoint.presence.wallet);
                    }

                    TransactionCache.addUnconfirmedTransaction(transaction);

                    Node.tiv.receivedNewTransaction(transaction);
                }
                break;

                case ProtocolMessageCode.bye:
                    CoreProtocolMessage.processBye(data, endpoint);
                    break;

                case ProtocolMessageCode.blockHeaders2:
                {
                    // Forward the block headers to the TIV handler
                    Node.tiv.receivedBlockHeaders2(data, endpoint);
                }
                break;

                case ProtocolMessageCode.pitData2:
                {
                    Node.tiv.receivedPIT2(data, endpoint);
                }
                break;

                default:
                    break;
                }
            }
            catch (Exception e)
            {
                Logging.error("Error parsing network message. Details: {0}", e.ToString());
            }
        }
Ejemplo n.º 29
0
 public void RemoveFromFriendList(User user)
 {
     FriendList.Remove(user);
 }
Ejemplo n.º 30
0
        // Read the account file from local storage
        public bool readAccountFile()
        {
            string account_filename = Path.Combine(documentsPath, accountFileName);

            if (File.Exists(account_filename) == false)
            {
                Logging.log(LogSeverity.error, "Cannot read account file.");

                // Generate a new wallet
                return(false);
            }

            BinaryReader reader;

            try
            {
                reader = new BinaryReader(new FileStream(account_filename, FileMode.Open));
            }
            catch (Exception e)
            {
                Logging.log(LogSeverity.error, String.Format("Cannot open account file. {0}", e.Message));
                return(false);
            }

            try
            {
                // TODO: decrypt data and compare the address/pubkey
                System.Int32 version        = reader.ReadInt32();
                int          address_length = reader.ReadInt32();
                byte[]       address        = reader.ReadBytes(address_length);
                string       nick           = reader.ReadString();

                nickname = nick;

                FriendList.clear();
                int num_contacts = reader.ReadInt32();
                for (int i = 0; i < num_contacts; i++)
                {
                    int friend_len = reader.ReadInt32();

                    Friend friend = new Friend(reader.ReadBytes(friend_len));

                    try
                    {
                        // Read messages from chat history
                        friend.messages = readLastMessages(friend.walletAddress);
                    }catch (Exception e)
                    {
                        Logging.error("Error reading contact's {0} messages: {1}", Base58Check.Base58CheckEncoding.EncodePlain(friend.walletAddress), e);
                    }

                    FriendList.addFriend(friend);
                }
            }
            catch (Exception e)
            {
                Logging.log(LogSeverity.error, String.Format("Cannot read from account file. {0}", e.Message));
            }

            reader.Close();

            return(true);
        }
Ejemplo n.º 31
0
 private void Initialize()
 {
     IP = new byte[4];
     ServerIp = new byte[4];
     LastLoginIp = new byte[4];
     IsLoggedIn = false;
     LoginMode = QQStatus.我在线上;
     IsUdp = true;
     ContactInfo = new ContactInfo();
     IsShowFakeCam = false;
     Friends = new FriendList(this);
     QQList = new QQList();
     ClusterList = new ClusterList();
     this.QQKey = new QQKey(this);
 }
 public void UpdateFriendList(FriendList friendList)
 {
     this.friendList = friendList;
     UpdatePage.UserSystemUpdate();
 }
Ejemplo n.º 33
0
 public void Update(string id, FriendList account)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 34
0
 public void AddToFriendList(User user)
 {
     FriendList.Add(user);
 }
Ejemplo n.º 35
0
 public DisplayFriendList(FriendList friends)
 {
     m_friendList = friends;
     InitializeComponent();
 }
Ejemplo n.º 36
0
        public ProfileViewModel CreateViewModel(UserAccount existingAccount, List <Group> GroupsWithUser, FriendUser existingFriend,
                                                FriendList FriendList, List <Request> FriendRequests, FriendList CurrentFriendList, List <Request> CurrentUserRequests)
        {
            var ProfileViewModel = new ProfileViewModel
            {
                FirstName        = existingAccount.FirstName,
                LastName         = existingAccount.LastName,
                Location         = existingAccount.Location,
                Email            = existingAccount.Email,
                Username         = existingAccount.Username,
                Occupation       = existingAccount.Occupation,
                UserType         = existingAccount.UserType,
                LastActive       = existingAccount.LastActive,
                JoinDate         = existingAccount.DateJoined,
                Groups           = GroupsWithUser,
                PendingRequest   = FriendRequests.FirstOrDefault(x => x.Username.Equals(_CurrentUser.UserName)),
                FriendListID     = FriendList.Id,
                ExistingFriend   = existingFriend,
                RequestToCurrent = CurrentUserRequests.FirstOrDefault(x => x.Username.Equals(existingAccount.Username))
            };

            return(ProfileViewModel);
        }
Ejemplo n.º 37
0
        public override void Execute(ref ConsoleSystem.Arg Arguments, ref string[] ChatArguments)
        {
            var    pl         = Fougerite.Server.Cache[Arguments.argUser.userID];
            string playerName = string.Join(" ", ChatArguments).Trim(new char[] { ' ', '"' });

            if (playerName == string.Empty)
            {
                pl.MessageFrom(Core.Name, "[color red]<Sintaxis> /unfriend <NombreJugador>");
                return;
            }
            FriendsCommand command     = (FriendsCommand)ChatCommand.GetCommand("amigos");
            FriendList     friendsList = (FriendList)command.GetFriendsLists()[pl.UID];

            if (friendsList == null)
            {
                pl.MessageFrom(Core.Name, "Actualmente no tienes amigos (Pvta ke sad).");
                return;
            }
            if (friendsList.isFriendWith(playerName))
            {
                friendsList.RemoveFriend(playerName);
                pl.MessageFrom(Core.Name, "Removiste a " + playerName + " de tu lista de amigos.");
                if (friendsList.HasFriends())
                {
                    command.GetFriendsLists()[pl.UID] = friendsList;
                }
                else
                {
                    command.GetFriendsLists().Remove(pl.UID);
                }
            }
            else
            {
                PList list = new PList();
                list.Add(0, "Cancel");
                foreach (KeyValuePair <ulong, string> entry in Core.userCache)
                {
                    if (friendsList.isFriendWith(entry.Key) && entry.Value.ToUpperInvariant().Contains(playerName.ToUpperInvariant()))
                    {
                        list.Add(entry.Key, entry.Value);
                    }
                }
                if (list.Count == 1)
                {
                    foreach (Fougerite.Player client in Fougerite.Server.GetServer().Players)
                    {
                        if (friendsList.isFriendWith(client.UID) && client.Name.ToUpperInvariant().Contains(playerName.ToUpperInvariant()))
                        {
                            list.Add(client.UID, client.Name);
                        }
                    }
                }
                if (list.Count == 1)
                {
                    pl.MessageFrom(Core.Name, string.Format("No eres amigo de {0}.", playerName));
                    return;
                }

                pl.MessageFrom(Core.Name, string.Format("{0}  amigo{1} {2}: ", ((list.Count - 1)).ToString(), (((list.Count - 1) > 1) ? "s encontrados" : " encontrado"), playerName));
                for (int i = 1; i < list.Count; i++)
                {
                    pl.MessageFrom(Core.Name, string.Format("{0} - {1}", i, list.PlayerList[i].DisplayName));
                }
                pl.MessageFrom(Core.Name, "0 - Cancelar");
                pl.MessageFrom(Core.Name, "Selecciona el amigo al que quieres eliminar.");
                Core.unfriendWaitList[pl.UID] = list;
            }
        }
Ejemplo n.º 38
0
 private void OnFriendsClick(object sender, RoutedEventArgs e)
 {
     FriendList.Display();
 }
Ejemplo n.º 39
0
    public override void Initialize()
    {
        base.Initialize();



        log.Debug("**** Going to get new client of main ****", this.ClientId);
        string newClientId = RootContext.GetNewClientId(this);

        log.Debug("**** Going to set new client of main ****", this.ClientId, newClientId);
        this.ClientId = newClientId;
        log.Debug("**** Set new client of main ****", this.ClientId);

        log.Debug("**** INIT TIME ****", this.ClientId);
        log.Warn("**** WARN INIT TIME ****", this.ClientId);

        log.Debug("**** apikey:", apikey);
        log.Debug("**** apisecret:", apisecret);

        foreach (var item in HttpContext.Current.Request.Params)
        {
            log.Debug("request item", item, HttpContext.Current.Request[(string)item]);
        }

        InitializeServices();

        if (Glyphs == null)
        {
            Glyphs = DataProvider.LoadList <Glyph>();
        }
        if (Tones == null)
        {
            Tones = DataProvider.LoadList <Tone>();
        }

        if (Glyphs.Count == 0)
        {
            Glyph.InitDataBase();
            Glyphs = DataProvider.LoadList <Glyph>();
        }
        if (Tones.Count == 0)
        {
            Tone.InitDataBase();
            Tones = DataProvider.LoadList <Tone>();
        }

        log.Debug("Tones", Tones);
        log.Debug("Glyphs", Glyphs);

        Now            = new DreamFolk();
        Now.FacebookId = "Now";
        Now.Birthday   = DateTime.Now;
        log.Warn("Now is " + Now.GetName(), Now, DateTime.Now, Now.Birthday);

        Label l = this.Find <Label>();

        if (l == null)
        {
            l = this.CreateWidget <Label>();
        }
        l.Text = DateTime.Now.ToShortDateString();


        // check to see if force records needs to be recalc
        if (HttpContext.Current.Request["recalc"] == "1")
        {
            log.Warn("RECALCULATING BIRTHDAYS!");
            //DataHelper helper = new DataHelper();
            //new Thread (new ThreadStart (helper.Recalc)).Start();
            ThreadPool.QueueUserWorkItem(new WaitCallback(Recalc));
        }
        else
        {
            log.Warn("skppping recalc", HttpContext.Current.Request["recalc"]);
        }

//			DreamSpellUtil.Calc();
//			log.Debug("Year Seal: " + DreamSpellUtil.CalcYearSeal());
//			log.Debug("Year Tone: " + DreamSpellUtil.CalcYearTone());
//			log.Debug("Distance From Day Out Of Time: " + DreamSpellUtil.CalcDistanceFromDayOutOfTime());
//			log.Debug("Year Seal: " + DreamSpellUtil.CalcSeal());
//			log.Debug("Year Tone: " + DreamSpellUtil.CalcTone());
//			DreamSpellUtil.CalcOracle();
//			log.Debug("Guide: " + DreamSpellUtil.Guide);
//			log.Debug("Antiopde: " + DreamSpellUtil.Antipode);
//			log.Debug("Analog: " + DreamSpellUtil.Analog);
//			log.Debug("Occult: " + DreamSpellUtil.Occult);
//			log.Debug("Kin: " + DreamSpellUtil.Kin);

        log.Debug("This HttpContext.Request", HttpContext.Current.Request);

        bool isAdded = HttpContext.Current.Request["fb_sig_added"] == "1";

        string owner_fb_id = HttpContext.Current.Request["owner_fb_id"];

        string sessionKey = HttpContext.Current.Request["fb_sig_session_key"];

        string userId = HttpContext.Current.Request["fb_sig_user"];

        log.Debug("isAdded", isAdded);
        log.Debug("owner_fb_id", owner_fb_id);
        log.Debug("sessionKey", sessionKey);
        log.Debug("userId", userId);

        if (userId != "775949236")
        {
            log.Debug("User is not me", userId);
            //return;
        }
        else
        {
            log.Debug("User is me!");
        }
        //return;
        log.Debug("Checking for nullOrEmpty sessionKey", sessionKey);

        if (string.IsNullOrEmpty(sessionKey))
        {
            log.Debug("No sessionKey");
            //this.HttpContext.Response.Redirect(@"http://www.facebook.com/login.php?api_key=" + apikey + @"&v=1.0");
            //return;
            log.Warn("No facebook session 1");

            StarSummary starSummary = Find <StarSummary>("StarHeader");
            if (starSummary != null)
            {
                starSummary.Visible = false;
            }

            Pane me = Find <Pane>("Me");
            //me.AppendClass("none");
            log.Warn("No facebook session 2");

            Pane friends = Find <Pane>("Friends");
            //friends.AppendClass("none");

            TabPane tabPane = Find <TabPane>();
            if (tabPane != null)
            {
                foreach (Pane pane in tabPane.tabsByLabels.Values)
                {
                    log.Debug("looking at pane: " + pane.Id);
                    if (pane.Id == "Me" || pane.Id == "Friends")
                    {
                        log.Debug("found either Me or Friends, going apply None: " + pane.Id);
                        pane.AppendClass("none");

                        //HtmlElement li = pane.FindAncestor
                        //li.AppendClass("none");
                    }
                }

                /*
                 * foreach (Object obj in tabPane.tabsByLabels.Keys)
                 * {
                 *      if ( ! (obj is HtmlElement) )
                 *      {
                 *              log.Debug("obj is not an  htmlElement",obj);
                 *              continue;
                 *      }
                 *
                 *      HtmlElement li = (HtmlElement)obj;
                 *      log.Debug("looking at key: " + li.Id + " " + li.TagName + " " + li.ClassName);
                 *
                 *      if ( li.ClassName == "MeTab" || li.ClassName == "FriendsTab" )
                 *      {
                 *              li.AppendClass("none");
                 *
                 *              //HtmlElement li = pane.FindAncestor
                 *              //li.AppendClass("none");
                 *
                 *      }
                 *      else
                 *              li.AppendClass("no-top-margin");
                 * }
                 */
            }
        }
        else
        {
            log.Debug(sessionKey, userId);

            IsFaceBookSession = true;

            if (sessionKey != null && userId != null)
            {
                handleFacebookUser(sessionKey, userId);
            }
        }

        if (CurrentDreamFriend == null)
        {
            log.Debug("Setting CurrentDreamFriend to Now");
            CurrentDreamFriend = Now;
        }
        log.Debug("Going to bind CurrentDreamFriend", CurrentDreamFriend);

//			ConfirmButton button = this.RootContext.CreateWidget<ConfirmButton>(this);
//			button.Label = "Recalc";
//			button.OnClick += delegate { ThreadPool.QueueUserWorkItem(new WaitCallback(Recalc)); };

        //this.RootContext.CreateWidget<FriendList>(this);

        //this.Record = Now;
        this.Record = CurrentDreamFriend;
        this.DataBindWidget(this.Record);

        log.Debug("Binded CurrentDreamFriend");

        Pane       todayPane   = this.Find <Pane>("Today");
        Pane       mePane      = this.Find <Pane>("Me");
        Pane       friendsPane = this.Find <Pane>("Friends");
        FriendList friendList  = this.Find <FriendList>();

        if (todayPane != null)
        {
            log.Debug("Binding todayPane");
            todayPane.DataBindWidget(Now);
        }

        if (mePane != null)
        {
            log.Debug("Binding mePane");
            mePane.DataBindWidget(CurrentDreamFriend);
        }

        if (friendsPane != null && friendList != null)
        {
            log.Debug("Binding friendsPane");
            friendsPane.DataBindWidget(CurrentDreamFriend);
            log.Debug("Binding friendList");
            friendList.DataBindWidget(CurrentDreamFriend);
        }

        log.Debug("Creating starHeaderNow");
        StarSummary starHeaderNow = this.Find <StarSummary>("StarHeaderNow");

        if (starHeaderNow != null)
        {
            log.Debug("Binding starHeaderNow");
            starHeaderNow.Record = Now;
            starHeaderNow.DataBindWidget();
        }
    }