示例#1
0
		public void DoWork ()
		{
			db = new DataBaseWrapper (Resources);
			network = new AsyncNetwork ();
			network.SetBackgroundService (this);
			user = db.Table<User>().FirstOrDefault ();
			var connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);

			if (user != null && user.user != null) {
				var t = new Thread (async () => {
					while (true) {
						Setting.Frequency f = db.Table<Setting>().FirstOrDefault().Synchronisation;
						if (f != Setting.Frequency.wlan || connectivityManager.GetNetworkInfo(ConnectivityType.Wifi).GetState() == NetworkInfo.State.Connected) {
							while(!await network.UpdateEvents (db, user)) {
								await network.Authenticate(db, user);
							}
						}

						// Wifi connection gets normal updates, other networks get 4 times worse update time.
						if (connectivityManager.GetNetworkInfo(ConnectivityType.Wifi).GetState() == NetworkInfo.State.Connected)
						{
							connectivityMode = 1;
						} else {
							connectivityMode = 4;
						}

						switch(f) {
						case Setting.Frequency.often:
							Mode = 1;
							break;
						case Setting.Frequency.normal:
							Mode = 2;
							break;
						case Setting.Frequency.rare:
							Mode = 4;
							break;
						case Setting.Frequency.wlan:
							Mode = 2;
							break;
						}

						Thread.Sleep (UpdateInterval * Mode* connectivityMode);

						if (UpdateInterval < 12000) {
							UpdateInterval += 1000;
						} else if (UpdateInterval < 30000) {
							UpdateInterval += 2000;
						} else {
							UpdateInterval = 120000;
						}
					}
				}
				);
				t.Start ();
			} else {
				StopSelf ();
			}
		}
示例#2
0
		protected override void OnCreate (Bundle bundle)
		{
			db = new DataBaseWrapper (this.Resources);
			if ((setting = db.Table<Setting> ().FirstOrDefault ()) == null) {
				db.Insert(setting = new Setting ());
			}
			StartupTheme = setting.Theme;
			SetTheme (setting.Theme);
			base.OnCreate (bundle);

			SetContentView (Resource.Layout.ChatActivity);

			conversation = Intent.GetStringExtra ("conversation");

			chat = db.Get<Chat> (conversation);
			visibleMessages = chat.VisibleMessages;
			if (visibleMessages <= 0) {
				visibleMessages = setting.VisibleMessages;
			}
			if (visibleMessages <= 0) {
				visibleMessages = 30;
			}
			Title = chat.name;
			ActionBar.SetDisplayHomeAsUpEnabled(true);
			ActionBar.SetIcon (Resource.Drawable.Icon);

			user = db.Table<User>().FirstOrDefault ();

			Button send = FindViewById<Button> (Resource.Id.send);
			send.Click += delegate {
				TextView message = FindViewById<TextView> (Resource.Id.message);
				var msg = message.Text;
				message.Text = "";

				if (msg.Equals("")) return;

				LinearLayout messageList = FindViewById<LinearLayout> (Resource.Id.messageLayout);
				AddMessage(messageList, new Message() {time = "sending", author = "Du", nick = user.user, text = msg, conversation = this.conversation});

				ScrollView scrollView = FindViewById<ScrollView> (Resource.Id.messageScrollView);
				scrollView.FullScroll (FocusSearchDirection.Down);
				scrollView.Post (() => scrollView.FullScroll (FocusSearchDirection.Down));

				OnBind();
				new Thread(async () => {
					while(!await network.SendMessage (db, user, chat, msg)) {
						await network.Authenticate(db, user);
					}
				}).Start();
			};
		}
示例#3
0
		protected override void OnCreate (Bundle bundle)
		{
			db = new DataBaseWrapper (this.Resources);
			if ((setting = db.Table<Setting> ().FirstOrDefault ()) == null) {
				db.Insert(setting = new Setting ());
			}
			SetTheme (setting.Theme);
			base.OnCreate (bundle);

			network = new AsyncNetwork ();
			db = new DataBaseWrapper (this.Resources);
			user = db.Table<User>().FirstOrDefault ();

			if (setting.FontSize == Setting.Size.large) {
				SetContentView (Resource.Layout.SettingsLarge);
			} else {
				SetContentView (Resource.Layout.Settings);
			}

			InitializeView();
		}
示例#4
0
		public Task<bool> UpdateHistory(DataBaseWrapper db, User user, Chat chat, int count)
		{
			string request = String.Format ("\"getHistory\":{{\"conversation\":\"{0}\", \"count\":\"{1}\"}}", chat.conversation, count);
			return CommonNetworkOperations (db, request, user, "onGetHistory", arr => {
				var msgs = arr ["messages"];
				string conversation = arr ["conversation"];

				foreach (JsonValue x in msgs) {
					try {
						var msg = new Message ();
						msg.conversation = conversation;
						msg.author = x ["author"];
						msg.nick = x ["nick"];
						msg.text = x ["text"];
						msg.time = x ["time"];
						db.InsertIfNotContains<Message>(msg);
					} catch (Exception e) {
						Log.Error ("BlaChat", e.StackTrace);
					}
				}
			});
		}
示例#5
0
		public async Task<bool> InjectEvent(DataBaseWrapper db, User user, Event e)
		{
			return true;
		}
示例#6
0
		public async Task<bool> Data(DataBaseWrapper db, User user, Chat chat, object data)
		{
			return true;
		}
示例#7
0
		public async Task<bool> Authenticate(DataBaseWrapper db, User user)
		{
			string encodedJson = escape (String.Format ("{{\"user\":\"{0}\", \"pw\":\"{1}\"}}", user.user, user.password));
			bool success = false;

			var result = JsonValue.Parse (await Download (user.server + "/xjcp.php?msg=" + encodedJson));
			try {
				if (result.ContainsKey ("id")) {
					user.id = result ["id"];
					db.Update (user);
					success = true;
				}
			} catch (Exception ex) {
				Log.Error ("BlaChat", ex.StackTrace);
			} finally {
				EventHandling (db, result);
			}

			return success && await EventHandling (db, result) == 0;
		}
示例#8
0
		public async Task<bool> SetGroupImage(DataBaseWrapper db, User user, Chat chat, object image)
		{
			return true;
		}
示例#9
0
		public Task<bool> SendMessage(DataBaseWrapper db, User user, Chat chat, string message)
		{
			message = message.Replace ("\\", "\\\\");
			message = message.Replace ("\"", "\\\"");
			string request = String.Format ("\"message\":{{\"conversation\":\"{0}\", \"message\":\"{1}\"}}", chat.conversation, message);
			return CommonNetworkOperations (db, request, user, "onMessage", x => { return; });
		}
示例#10
0
		private void ShowChats(User user) {
			TextView placeholder = FindViewById<TextView> (Resource.Id.placeholder);
			var x = db.Table<Chat> ();
			if (x.Count() > 0) {
				placeholder.Visibility = ViewStates.Gone;
			} else {
				placeholder.Visibility = ViewStates.Visible;
				placeholder.Text = "No chats found.";
			}
			LinearLayout chatList = FindViewById<LinearLayout> (Resource.Id.chatList);
			chatList.RemoveAllViews ();
			foreach (var elem in x.OrderByDescending(e => e.time)) {
				View v;
				if (setting.FontSize == Setting.Size.large) {
					v = LayoutInflater.Inflate (Resource.Layout.ChatLarge, null);
				} else {
					v = LayoutInflater.Inflate (Resource.Layout.Chat, null);
				}
				TextView name = v.FindViewById<TextView>(Resource.Id.chatName);
				TextView message = v.FindViewById<TextView>(Resource.Id.chatMessage);
				TextView time = v.FindViewById<TextView>(Resource.Id.chatTime);
				ImageView image = v.FindViewById<ImageView> (Resource.Id.chatImage);

				if (elem.Marked) {
					message.SetTextColor(Color.Green);
				}

				new Thread (async () => {
					try {
						string conv = elem.conversation;
						if (conv.Split(',').Length == 2) {
							if (conv.Split(',')[0] == user.user) {
								conv = conv.Split(',')[1];
							} else {
								conv = conv.Split(',')[0];
							}
						}
						var imageBitmap = await network.GetImageBitmapFromUrl(Resources.GetString(Resource.String.profileUrl) + conv + ".png");
						RunOnUiThread(() => image.SetImageBitmap(imageBitmap));
					} catch (Exception e) {
						Log.Error("BlaChat", e.StackTrace);
					}
				}).Start();

				name.TextFormatted = SpannableTools.GetSmiledText (this, new SpannableString(elem.name));
				var tmp = db.Table<Message> ().Where (q => q.conversation == elem.conversation).OrderByDescending (q => q.time);
				var lastMsg = tmp.FirstOrDefault ();
				if (lastMsg != null) {
					var escape = lastMsg.text.Replace ("&quot;", "\"");
					escape = escape.Replace ("&lt;", "<");
					escape = escape.Replace ("&gt;", ">");
					escape = escape.Replace ("&amp;", "&");
					if (escape.StartsWith ("#image")) {
						escape = "(image)";
					} else if (escape.StartsWith ("#video")) {
						escape = "(video)";
					}
					if (lastMsg.nick == user.user) {
						message.TextFormatted = SpannableTools.GetSmiledText (this, new SpannableString("Du: " + escape));
					} else {
						if (elem.conversation.Split (',').Length == 2 && lastMsg.nick != "watchdog") {
							message.TextFormatted = SpannableTools.GetSmiledText (this, new SpannableString(escape));
						} else {
							message.TextFormatted = SpannableTools.GetSmiledText (this, new SpannableString(lastMsg.author + ": " + escape));
						}
					}
					time.Text = TimeConverter.AutoConvert(lastMsg.time);
				} else {
					time.Text = "";
					message.Text = "No message";
				}

				v.Clickable = true;
				v.Click += delegate {
					var intent = new Intent (this, typeof(ChatActivity));
					intent.PutExtra ("conversation", elem.conversation);
					StartActivity (intent);
				};
				chatList.AddView(v);
			}
			chatList.Post(() => chatList.RequestLayout ());
		}
示例#11
0
		private void initializeAuthenticated(User user) {
			SetContentView (Resource.Layout.Main);
			ShowChats (user);
		}
示例#12
0
		private void UpdateMessagesScrollDown(User user) {
				UpdateMessages (user);

				ScrollView scrollView = FindViewById<ScrollView> (Resource.Id.messageScrollView);
				scrollView.FullScroll (FocusSearchDirection.Down);
				scrollView.Post (() => scrollView.FullScroll (FocusSearchDirection.Down));
		}
示例#13
0
		public async Task<bool> RemoveEvent(DataBaseWrapper db, User user, Event e)
		{
			string encodedJson = escape(String.Format("{{\"id\":\"{0}\", \"removeEvent\":{{\"conversation\":\"{1}\"}}}}", user.id, e.msg));

			var result = JsonValue.Parse(await Download(user.server + "/xjcp.php?msg=" + encodedJson));
			var success = false;
			try {
				success = 0 == await EventHandling (db, result);
			} catch (Exception ex) {
				Log.Error ("BlaChat", ex.StackTrace);
			}

			return success;
		}
示例#14
0
		public async Task<bool> NewChat(DataBaseWrapper db, User user, List<User> users, string name)
		{
			return true;
		}
示例#15
0
		private async Task<bool> InternalUpdateEvents(DataBaseWrapper db, User user) {
			string encodedJson = escape (String.Format ("{{\"id\":\"{0}\"}}", user.id));

			var result = JsonValue.Parse (await Download (user.server + "/xjcp.php?msg=" + encodedJson));
			var success = false;
			try {
				success = 0 == await EventHandling (db, result);
			} catch (Exception ex) {
				Log.Error ("BlaChat", ex.StackTrace);
			}

			updateEventTask = null;

			return success;
		}
示例#16
0
		public Task<bool> UpdateEvents(DataBaseWrapper db, User user)
		{
			lock (taskCacheLocker) {
				if (updateEventTask == null) {
					updateEventTask = InternalUpdateEvents(db, user);
				}
				return updateEventTask;
			}
		}
示例#17
0
		public async Task<bool> SendImage (DataBaseWrapper db, User user, Chat chat, Bitmap bitmap)
		{
			string encodedJson = escape (String.Format ("{{\"id\":\"{0}\", \"data\":{{\"conversation\":\"{1}\"}}}}", user.id, chat.conversation));
			var success = false;
            NameValueCollection nvc = new NameValueCollection();
            nvc.Add("msg", encodedJson);
			string tmp = null;
			while (tmp == null) {
				tmp = HttpUploadFile (user.server + "/xjcp.php", bitmap, "uploadedfile", "image/png", nvc);
			}
			var result = JsonValue.Parse (tmp);

			try {
				success = 0 == await EventHandling (db, result);

				if (!result.ContainsKey ("onData")) {
					success = false;
				}
			} catch (Exception ex) {
				Log.Error ("BlaChat", ex.StackTrace);
			}

			return success;
		}
示例#18
0
		private async Task<int> HandleEvent(DataBaseWrapper db, AsyncNetwork network, User user, Event e) {
			if (e.type != "onMessage") {
				return 0;
			}
			var chat = db.Get<Chat> (e.msg);
			if (chat == null) {
				while(!await network.UpdateChats (db, user)) {
					await network.Authenticate(db, user);
				}
				chat = db.Get<Chat> (e.msg);
			}
			chat.time = e.time;
			db.Update (chat);

			var msg = new Message ();
			msg.conversation = chat.conversation;
			msg.author = e.author;
			msg.nick = e.nick;
			msg.text = e.text;
			msg.time = e.time;
			db.InsertIfNotContains<Message> (msg);

			ResetUpdateInterval ();
			if (e.msg != ActiveConversation && user.user != e.nick) {
				chat.Marked = true;
				db.Update (chat);
				if (chat.Notifications) {
					await Notify (network, e.nick, e.text);
				}
			}
			if (ChatActivity != null) {
				ChatActivity.OnUpdateRequested ();
			} else if (MainActivity != null) {
				MainActivity.OnUpdateRequested ();
			}
			return 0;
		}
示例#19
0
		public Task<bool> UpdateChats(DataBaseWrapper db, User user)
		{
			string request = String.Format ("\"getChats\":{{}}");

			return CommonNetworkOperations(db, request, user, "onGetChats", x => {
				JsonArray arr = (JsonArray)x;
				foreach (JsonValue v in arr) {
					string conv = v ["conversation"];
					var chat = db.Get<Chat> (conv);
					if (chat == null) {
						chat = new Chat () {
							conversation = conv
						};
						db.Insert (chat);
					}
					chat.name = v ["name"];
					chat.time = v ["time"];
					db.Update (chat);
				}
			});
		}
示例#20
0
		public async Task<bool> RenameChat(DataBaseWrapper db, User user, Chat chat, string name)
		{
			return true;
		}
示例#21
0
		public Task<bool> UpdateContacts(DataBaseWrapper db, User user)
		{
			string request = String.Format ("\"getContacts\":{{}}");

			return CommonNetworkOperations (db, request, user, "onGetContacts", x => {
				JsonArray arr = (JsonArray)x;
				foreach (JsonValue v in arr) {
					var contact = db.Get<Contact> (v ["nick"]);
					if (contact == null) {
						contact = new Contact () {
							nick = v ["nick"]
						};
						db.Insert (contact);
					}
					contact.name = v ["name"];
					contact.status = v ["status"];
					db.Update (contact);
				}
			});
		}
示例#22
0
		public async Task<bool> SetName(DataBaseWrapper db, User user, string name)
		{
			return true;
		}
示例#23
0
		public async Task<bool> AddFriend(DataBaseWrapper db, User user, string name)
		{
			return true;
		}
示例#24
0
		private void UpdateMessages(User user) {
			LinearLayout messageList = FindViewById<LinearLayout> (Resource.Id.messageLayout);
			messageList.RemoveAllViews ();
			var x = db.Table<Message> ();
			List<Message> tmp = x.Where(q => q.conversation == conversation).OrderBy(e => e.time).Reverse().Take(visibleMessages).Reverse().ToList();
			string prevDate = "0000-00-00";
			foreach (var elem in tmp) {
				if (!elem.time.StartsWith (prevDate)) {
					prevDate = TimeConverter.Convert (elem.time, "yyyy-MM-dd");
					View timeInsert;
					if (setting.FontSize == Setting.Size.large) {
						timeInsert = LayoutInflater.Inflate (Resource.Layout.TimeInsertLarge, null);
					} else {
						timeInsert = LayoutInflater.Inflate (Resource.Layout.TimeInsert, null);
					}
					TextView text = timeInsert.FindViewById<TextView> (Resource.Id.timeInsertTime);
					text.Text = TimeConverter.AutoConvertDate (elem.time);
					messageList.AddView(timeInsert);
				}

				AddMessage (messageList, elem);
			}
			messageList.Post(() => messageList.RequestLayout ());
		}
示例#25
0
		public async Task<bool> SetStatus(DataBaseWrapper db, User user, string status)
		{
			return true;
		}
示例#26
0
		private void initializeAuthenticated(User user) {
			StartService (new Intent (this, typeof(BackgroundService)));

			if (service == null) {
				var sericeIntent = new Intent (this, typeof(BackgroundService));
				serviceConnection = new ServiceConnection (this);
				BindService (sericeIntent, serviceConnection, Bind.AutoCreate);
			}

			SetContentView (Resource.Layout.Main);
			ShowChats (user);
		}
示例#27
0
		public async Task<bool> SetProfileImage(DataBaseWrapper db, User user, object image)
		{
			return true;
		}
示例#28
0
		private void initializeNotAuthenticated() {
			SetContentView (Resource.Layout.Authentication);

			Button login = FindViewById<Button> (Resource.Id.login);
			login.Click += async delegate {

				InputMethodManager manager = (InputMethodManager) GetSystemService(InputMethodService);
				manager.HideSoftInputFromWindow(FindViewById<EditText> (Resource.Id.username).WindowToken, 0);
				manager.HideSoftInputFromWindow(FindViewById<EditText> (Resource.Id.password).WindowToken, 0);
				manager.HideSoftInputFromWindow(FindViewById<EditText> (Resource.Id.server).WindowToken, 0);

				login.Text = "Connecting...";
				login.Enabled = false;

				var user = new User() {
					user = FindViewById<EditText> (Resource.Id.username).Text.ToLower(),
					password = FindViewById<EditText> (Resource.Id.password).Text,
					server = !string.IsNullOrEmpty (FindViewById<EditText> (Resource.Id.server).Text) ?
						FindViewById<EditText> (Resource.Id.server).Text :
						FindViewById<EditText> (Resource.Id.server).Hint
				};
				if (user.user == "" || user.password == "") {
					login.Text = "Login";
					login.Enabled = true;
					return;
				}

				if(await network.Authenticate(db, user)) {
					login.Text = "Loading data...";
					new Thread(async () => {
						int i = 0;
						db.Insert(user);
						while(!await network.UpdateChats (db, user)) {
							await network.Authenticate(db, user);
						}
						var x = db.Table<Chat> ();
						int count = x.Count();
						var tasks = new List<Task<bool>>();
						RunOnUiThread(() => initializeAuthenticated(user));

						foreach (var chat in x) {
							while(!await network.UpdateHistory(db, user, chat, 30)) {
								await network.Authenticate(db, user);
							}
							OnUpdateRequested();
						}
					}).Start();
				} else {
					login.Text = "Retry Login";
					login.Enabled = true;
				}
			};
		}
示例#29
0
		private async Task<bool> CommonNetworkOperations(DataBaseWrapper db, String request, User user, String actionKey, Action<JsonValue> action) {
			string encodedJson = escape (String.Format ("{{\"id\":\"{0}\", {1}}}", user.id, request));
			var result = JsonValue.Parse (await Download (user.server + "/xjcp.php?msg=" + encodedJson));
			bool success = false;
			try {
				if (result.ContainsKey (actionKey)) {
					action.Invoke(result [actionKey]);
					success = true;
				}
			} catch (Exception ex) {
				Log.Error ("BlaChat", ex.StackTrace);
			}

			return success && await EventHandling (db, result) == 0;
		}