private void OnMessage(WebSocketEventArgs evt) { Pusher.Log("Pusher : OnMessage : ", evt.TextData); JsonData paramss = JSON.parse(evt.TextData); if (paramss.ContainsKey("socket_id") && paramss["socket_id"].ToString() == this.socket_id) { return; } // Try to parse the event data unless it has already been decoded if (paramss["data"] is string) { paramss["data"] = Pusher.Parser((string)paramss["data"]); } Pusher.Log("Pusher : received message : ", paramss); if (paramss.ContainsKey("channel")) { this.SendLocalEvent((string)paramss["event"], paramss["data"], (string)paramss["channel"]); } else { this.SendLocalEvent((string)paramss["event"], paramss["data"]); } }
void CandidateWebSocketHandler(object sender, WebSocketEventArgs args) { WebSocketInfo wi = args.Info; CandidateInfo info = (CandidateInfo)wi.State; var msg = DynamicJson.Parse (JSONEncoding.GetString (args.Payload, 0, (int)args.PayloadSize)); string errMsg = string.Empty; if (info.State == CandidateState.Initialized) { Console.WriteLine ("[CandidateHandler] Initialized"); long key; if (!msg.IsDefined ("e") || !msg.IsDefined ("s") || !long.TryParse (msg.e, out key)) { errMsg = "msg format error"; goto OnError; } JoinInfo join_info = null; lock (waitings_) { if (!waitings_.TryGetValue (key, out join_info)) { errMsg = "ignore"; goto OnError; } waitings_.Remove (key); } join_info.CandidatePeer = wi; info.Info = join_info; info.State = CandidateState.IceProcess; dynamic msg2 = new DynamicJson (); msg2.r = "ok"; msg2.s = msg.s; join_info.RequestedPeer.Send (msg2.ToString (), JSONEncoding); Console.WriteLine ("[CandidateHandler] Relay SDP to join requested peer"); lock(join_info.IceQueue) { foreach(string ice_cand in join_info.IceQueue) { msg2 = new DynamicJson(); msg2.ice = ice_cand; Console.WriteLine("[CandidateHandler] Relay Queued Ice Candidates"); info.Info.RequestedPeer.Send(msg2.ToString(), JSONEncoding); } } return; } if (info.State == CandidateState.IceProcess) { dynamic msg2 = new DynamicJson(); msg2.ice = msg.ice; Console.WriteLine("[CandidateHandler] Relay Ice Candidates"); info.Info.RequestedPeer.Send(msg2.ToString(), JSONEncoding); return; } OnError: Console.WriteLine("[CandidateHandler] ERROR: {0}", errMsg); dynamic retMsg = new DynamicJson (); retMsg.r = errMsg; wi.Send (retMsg.ToString (), JSONEncoding); wi.Close (); }
public void OnWebSocketEvent(WebSocketEventArgs args) { DebugHandler.TraceMessage("OnWebSocketEvent Called", DebugSource.TASK, DebugType.ENTRY_EXIT); DebugHandler.TraceMessage(args.ToString(), DebugSource.TASK, DebugType.PARAMETERS); try { try{ JObject query = JObject.Parse(args.Message); string action = query.Value <string>("action"); if (action != null) { JObject extra = query.Value <JObject>("extra"); if (extra != null) { switch (action) { case "delete_file": FileWebSocketService.DeleteFile(extra); break; case "open_file": FileWebSocketService.OpenFile(extra); break; } } } } catch (JsonReaderException e) { DebugHandler.TraceMessage(e.ToString(), DebugSource.TASK, DebugType.WARNING); JsonError error = new JsonError() { type = "command_error", errormessage = "Error happend during parsing of command.", errortype = "exception", exception = e.ToString() }; WebSocketHandler.SendMessage(error.ToJson()); } } catch (Exception e) { DebugHandler.TraceMessage(e.ToString(), DebugSource.TASK, DebugType.ERROR); JsonError error = new JsonError() { type = "command_error", errormessage = "Error happend during execution of command.", errortype = "exception", exception = e.ToString() }; WebSocketHandler.SendMessage(error.ToJson()); } }
private void ClientEventsWebSocket_Accept(object Sender, WebSocketEventArgs e) { HttpFieldCookie Cookie; if ((Cookie = e.Socket.HttpRequest.Header.Cookie) is null || string.IsNullOrEmpty(Cookie["HttpSessionID"])) { throw new ForbiddenException("HTTP Session required."); } }
public void HandleWebSocketEvent(object origin, WebSocketEventArgs args) { if (args.Type != EventType.Rx) { return; } var messages = JsonConvert.DeserializeObject <BulkControlMessage>(args.Data); this.PostMeasurements(messages.Messages.ToList(), messages.SensorId).GetAwaiter().GetResult(); }
private void OnWebSocketEvent(object sender, WebSocketEventArgs args) { DebugHandler.TraceMessage("OnWebSocketEvent called", DebugSource.TASK, DebugType.ENTRY_EXIT); try{ foreach (ISubWebSocketController controller in SubControllers) { controller.OnWebSocketEvent(args); } } catch (Exception e) { DebugHandler.TraceMessage(e.ToString(), DebugSource.TASK, DebugType.ERROR); } }
private void EvaluationWebSocketHandler_MessageReceived(Object sender, WebSocketEventArgs e) { WebSocket webSocket = (WebSocket)sender; if (e.Json.Value <String>("sender") == "player") { Task.Run(() => this.PlayerMessageReceivedAsync(e.Json.Value <JObject>("data"), webSocket, e.Json.Value <String>("action"))).Wait(); } else if (e.Json.Value <String>("sender") == "presenter") { Task.Run(() => this.PresenterMessageReceivedAsync(e.Json.Value <JObject>("data"), webSocket, e.Json.Value <String>("action"))).Wait(); } else { Task.Run(() => this.OwnerMessageReceivedAsync(e.Json.Value <JObject>("data"), webSocket, e.Json.Value <String>("action"))).Wait(); } }
public void HandleWebSocketEvent(object sender, WebSocketEventArgs args) { switch (args.Type) { case EventType.Rx: case EventType.Connected: break; case EventType.Ping: logger.Info($"PONG received from {sender.GetType().Name}"); Interlocked.Exchange(ref this.m_unansweredPings, 0); break; default: throw new ArgumentOutOfRangeException(); } }
/// <summary> /// Event handler for WebSocket data. /// </summary> /// <param name="sender">The sender object.</param> /// <param name="e">Event arguments.</param> private void OnSocketData(object sender, WebSocketEventArgs e) { try { BaseFrame frame = this.serializer.Deserialize(e.BinaryData); if (this.OnFrameReceived != null) { this.OnFrameReceived(this, new FrameEventArgs(frame)); } try { if (frame is DataFrame) { this.ProcessDataFrame((DataFrame)frame); } else if (frame is ControlFrame) { this.ProcessControlFrame((ControlFrame)frame); } else { throw new InvalidOperationException("Unsupported frame type"); } } catch (Exception streamError) { if (streamError is SMProtocolExeption || this.OnStreamError == null) { throw; } this.OnStreamError(this, new StreamErrorEventArgs(this.streamsStore.GetStreamById(frame.StreamId), streamError)); } } catch (Exception protocolError) { if (this.OnError != null) { this.OnError(this, new SMProtocolErrorEventArgs(protocolError)); } } }
private static void WebSocket_Event(object sender, WebSocketEventArgs args) { var service = sender as IListener; switch (args.Type) { case EventType.Connected: service?.AuthorizeUserAsync(CancellationToken.None).GetAwaiter().GetResult(); Thread.Sleep(500); service?.AuthorizeSensorsAsync(CancellationToken.None).GetAwaiter().GetResult(); break; case EventType.Rx: case EventType.Ping: break; default: throw new ArgumentOutOfRangeException(); } }
public void HandleWebSocketEvent(object origin, WebSocketEventArgs args) { switch (args.Type) { case EventType.Rx: this.m_logger.Info("Received DSMR message."); var parsed = this.ParseControlMessages(args.Data).ToList(); var removed = parsed.RemoveAll(t => t == null); this.m_logger.Info($"Writing {parsed.Count} measurements to Sensate IoT. {removed} have " + "been discarded due to parsing issues."); this.processMeasurements(parsed); break; case EventType.Connected: case EventType.Ping: break; default: throw new ArgumentOutOfRangeException(); } }
public void OnWebSocketEvent(WebSocketEventArgs args) { DebugHandler.TraceMessage("OnWebSocketEvent called", DebugSource.TASK, DebugType.ENTRY_EXIT); DebugHandler.TraceMessage(args.ToString(), DebugSource.TASK, DebugType.PARAMETERS); try { try { JObject query = JObject.Parse(args.Message); string action = query.Value <string>("action"); if (action != null) { JObject extra = query.Value <JObject>("extra"); if (extra != null) { switch (action) { case "get_files_for_anime": InfoApiWebSocketService.GetFilesForAnime(extra); break; case "get_anime_profile": InfoApiWebSocketService.GetAnimeProfile(extra); break; } } else { switch (action) { case "get_currently_airing": InfoApiWebSocketService.GetCurrentlyAiring(); break; } } } } catch (JsonReaderException e) { DebugHandler.TraceMessage(e.ToString(), DebugSource.TASK, DebugType.WARNING); JsonError error = new JsonError() { type = "command_error", errormessage = "Error happend during parsing of command.", errortype = "exception", exception = e.ToString() }; WebSocketHandler.SendMessage(error.ToJson()); } } catch (Exception e) { DebugHandler.TraceMessage(e.ToString(), DebugSource.TASK, DebugType.ERROR); JsonError error = new JsonError() { type = "command_error", errormessage = "Error happend during execution of command.", errortype = "exception", exception = e.ToString() }; WebSocketHandler.SendMessage(error.ToJson()); } }
public void OnWebSocketEvent(WebSocketEventArgs args) { DebugHandler.TraceMessage("OnWebSocketEvent Called", DebugSource.TASK, DebugType.ENTRY_EXIT); DebugHandler.TraceMessage(args.ToString(), DebugSource.TASK, DebugType.PARAMETERS); try { try{ JObject query = JObject.Parse(args.Message); string action = query.Value <string>("action"); if (action != null) { JObject extra = query.Value <JObject>("extra"); if (extra != null) { switch (action) { case "connect_irc": IrcWebSocketService.Connect(extra); break; case "sendmessage_irc": IrcWebSocketService.SendMessage(extra); break; } } else { switch (action) { case "get_irc_data": IrcWebSocketService.GetCurrentIrcSettings(); break; case "connect_irc": IrcWebSocketService.Connect(); break; case "disconnect_irc": IrcWebSocketService.Disconnect(); break; case "enablechat_irc": IrcWebSocketService.EnableSendMessage(); break; case "disablechat_irc": IrcWebSocketService.DisableSendMessage(); break; } } } } catch (JsonReaderException e) { DebugHandler.TraceMessage(e.ToString(), DebugSource.TASK, DebugType.WARNING); JsonError error = new JsonError() { type = "command_error", errormessage = "Error happend during parsing of command.", errortype = "exception", exception = e.ToString() }; WebSocketHandler.SendMessage(error.ToJson()); } } catch (Exception e) { DebugHandler.TraceMessage(e.ToString(), DebugSource.TASK, DebugType.ERROR); JsonError error = new JsonError() { type = "command_error", errormessage = "Error happend during execution of command.", errortype = "exception", exception = e.ToString() }; WebSocketHandler.SendMessage(error.ToJson()); } }
public void OnWebSocketEvent(WebSocketEventArgs args) { DebugHandler.TraceMessage("OnWebSocketEvent Called", DebugSource.TASK, DebugType.ENTRY_EXIT); DebugHandler.TraceMessage(args.ToString(), DebugSource.TASK, DebugType.PARAMETERS); try { try{ JObject query = JObject.Parse(args.Message); string action = query.Value <string>("action"); if (action != null) { JObject extra = query.Value <JObject>("extra"); if (extra != null) { switch (action) { case "set_littleweeb_settings": SettingsWebSocketService.SetLittleWeebSettings(extra); break; case "set_irc_settings": SettingsWebSocketService.SetIrcSettings(extra); break; case "set_download_directory": SettingsWebSocketService.Setfullfilepath(extra); break; } } else { switch (action) { case "get_littleweeb_settings": SettingsWebSocketService.GetCurrentLittleWeebSettings(); break; case "get_irc_settings": SettingsWebSocketService.GetCurrentIrcSettings(); break; } } } } catch (JsonReaderException e) { DebugHandler.TraceMessage(e.ToString(), DebugSource.TASK, DebugType.WARNING); JsonError error = new JsonError() { type = "command_error", errormessage = "Error happend during parsing of command.", errortype = "exception", exception = e.ToString() }; WebSocketHandler.SendMessage(error.ToJson()); } } catch (Exception e) { DebugHandler.TraceMessage(e.ToString(), DebugSource.TASK, DebugType.ERROR); JsonError error = new JsonError() { type = "command_error", errormessage = "Error happend during execution of command.", errortype = "exception", exception = e.ToString() }; WebSocketHandler.SendMessage(error.ToJson()); } }
private void ClientEventsWebSocket_Connected(object Sender, WebSocketEventArgs e) { e.Socket.Closed += Socket_Closed; e.Socket.Disposed += Socket_Disposed; e.Socket.TextReceived += Socket_TextReceived; }
/// <summary> /// Listens to the WebSocket message received event. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="WebSocketClient.WebSocketEventArgs"/> instance containing the event data.</param> private void MessageReceived(object sender, WebSocketEventArgs e) { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "TurntableBot OnMessage. Thread ID: {0}", Thread.CurrentThread.ManagedThreadId)); WebSocket ws = (WebSocket)sender; string data = this.ParseRawTurntableMessage(e.Data); if (data.StartsWith(HeartbeatSeparator, StringComparison.OrdinalIgnoreCase)) { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "TurntableBot OnMessage Heartbeat. Thread ID: {0}", Thread.CurrentThread.ManagedThreadId)); this.LastHeartbeat = DateTime.UtcNow; this.PresenceSet(Presence.Available); this.Send(data); } else if (data.Equals("no_session", StringComparison.OrdinalIgnoreCase)) { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "TurntableBot OnMessage No Session. Thread ID: {0}", Thread.CurrentThread.ManagedThreadId)); if (!this.isConnected) { this.UserAuthenticate(); } this.PresenceSet( Presence.Available, delegate(JObject delegateJson) { if (this.connectDelegate != null) { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "TurntableBot OnMessage Connecting to room. Thread ID: {0}", Thread.CurrentThread.ManagedThreadId)); this.connectDelegate(); } else { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "TurntableBot OnMessage Not in a room. Thread ID: {0}", Thread.CurrentThread.ManagedThreadId)); this.OnNoRoomWhenConnected(); } }); } else { this.LastActivity = DateTime.UtcNow; JObject json = JObject.Parse(data); int msgId = (int?)json["msgid"] ?? -1; if (this.commands.ContainsKey(msgId)) { string api = (string)this.commands[msgId].Message["api"] ?? string.Empty; Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "TurntableBot OnMessage Received response to sent message. Thread ID: {0}. Message ID: {1}. Api: {2}.", Thread.CurrentThread.ManagedThreadId, msgId, api)); if (api.Equals("user.authenticate", StringComparison.OrdinalIgnoreCase)) { if ((bool?)json["success"] ?? false) { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "TurntableBot OnMessage Received Authentication success. Thread ID: {0}.", Thread.CurrentThread.ManagedThreadId)); this.isConnected = true; this.OnAuthenticated(); } else { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "TurntableBot OnMessage Received Authentication failed. Thread ID: {0}.", Thread.CurrentThread.ManagedThreadId)); this.Disconnect(false); return; } } else if (api.Equals("room.info", StringComparison.OrdinalIgnoreCase)) { if ((bool?)json["success"] ?? false) { JObject currentSong = null; try { currentSong = (JObject)json["room"]["metadata"]["current_song"]; } catch (NullReferenceException) { } catch (InvalidCastException) { } if (currentSong != null) { this.CurrentSongId = (string)currentSong["_id"]; } } } else if (api.Equals("room.register", StringComparison.OrdinalIgnoreCase)) { if ((bool?)json["success"] ?? false) { this.RoomId = (string)this.commands[msgId].Message["roomid"]; this.RoomInfo( false, delegate(JObject delegateJson) { this.OnRoomChanged(delegateJson); this.OnNewSongStarted(delegateJson); }); } } else if (api.Equals("room.deregister", StringComparison.OrdinalIgnoreCase)) { if ((bool?)json["success"] ?? false) { this.RoomId = null; this.CurrentSongId = null; this.OnSongEnded(); } } if (this.commands[msgId].Callback != null) { this.commands[msgId].Callback(json); } this.commands.Remove(msgId); } string command = (string)json["command"] ?? string.Empty; if (!string.IsNullOrEmpty(command)) { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "TurntableBot OnMessage Command received. Thread ID: {0}. Command: {1}", Thread.CurrentThread.ManagedThreadId, command)); if (command.Equals("killdashnine", StringComparison.OrdinalIgnoreCase)) { this.Disconnect(false); this.OnKillDashNined(json); } else if (command.Equals("registered", StringComparison.OrdinalIgnoreCase)) { this.OnUserRegistered(json); } else if (command.Equals("deregistered", StringComparison.OrdinalIgnoreCase)) { this.OnUserDeregistered(json); } else if (command.Equals("speak", StringComparison.OrdinalIgnoreCase)) { this.OnUserSpoke(json); } else if (command.Equals("nosong", StringComparison.OrdinalIgnoreCase)) { this.CurrentSongId = null; this.OnSongEnded(); this.OnNoSongPlaying(json); } else if (command.Equals("newsong", StringComparison.OrdinalIgnoreCase)) { if (this.CurrentSongId != null) { this.OnSongEnded(); } this.CurrentSongId = (string)json["room"]["metadata"]["current_song"]["_id"]; this.OnNewSongStarted(json); } else if (command.Equals("update_votes", StringComparison.OrdinalIgnoreCase)) { this.OnVotesUpdated(json); } else if (command.Equals("booted_user", StringComparison.OrdinalIgnoreCase)) { this.OnUserBooted(json); } else if (command.Equals("update_user", StringComparison.OrdinalIgnoreCase)) { this.OnUserUpdated(json); } else if (command.Equals("add_dj", StringComparison.OrdinalIgnoreCase)) { this.OnDJAdded(json); } else if (command.Equals("rem_dj", StringComparison.OrdinalIgnoreCase)) { this.OnDJRemoved(json); } else if (command.Equals("new_moderator", StringComparison.OrdinalIgnoreCase)) { this.OnModeratorAdded(json); } else if (command.Equals("rem_moderator", StringComparison.OrdinalIgnoreCase)) { this.OnModeratorRemoved(json); } else if (command.Equals("snagged", StringComparison.OrdinalIgnoreCase)) { this.OnSongSnagged(json); } else { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", command, json)); } } if (msgId > 0) { if (json["success"] != null && !(bool)json["success"]) { Debug.WriteLine(json); } } if (json["err"] != null) { Debug.WriteLine(json); } } }
public void OnWebSocketEvent(WebSocketEventArgs args) { DebugHandler.TraceMessage("OnWebSocketEvent Called", DebugSource.TASK, DebugType.ENTRY_EXIT); DebugHandler.TraceMessage(args.ToString(), DebugSource.TASK, DebugType.PARAMETERS); try { try { JObject query = JObject.Parse(args.Message); string action = query.Value <string>("action"); if (action != null) { JObject extra = query.Value <JObject>("extra"); if (extra != null) { switch (action) { case "add_download": DownloadWebSocketService.AddDownload(extra); break; case "add_downloads": DownloadWebSocketService.AddDownloads(extra); break; case "abort_download": DownloadWebSocketService.AbortDownload(extra); break; case "remove_download": DownloadWebSocketService.RemoveDownload(extra); break; } } else { switch (action) { case "get_downloads": DownloadWebSocketService.GetCurrentFileHistory(); break; case "get_free_space": DirectoryWebSocketService.GetFreeSpace(); break; case "open_download_directory": DownloadWebSocketService.Openfullfilepath(); break; } } } } catch (JsonReaderException e) { DebugHandler.TraceMessage(e.ToString(), DebugSource.TASK, DebugType.WARNING); JsonError error = new JsonError() { type = "command_error", errormessage = "Error happend during parsing of command.", errortype = "exception", exception = e.ToString() }; WebSocketHandler.SendMessage(error.ToJson()); } } catch (Exception e) { DebugHandler.TraceMessage(e.ToString(), DebugSource.TASK, DebugType.ERROR); JsonError error = new JsonError() { type = "command_error", errormessage = "Error happend during execution of command.", errortype = "exception", exception = e.ToString() }; WebSocketHandler.SendMessage(error.ToJson()); } }
/// <summary> /// Event for when debug messages from the websocket server are available. /// </summary> static void WsDebugReceived(object sender, WebSocketEventArgs args) { string msg = args.Message; Console.WriteLine(msg); }
/// <summary> /// Event for when data is received over websockets. /// </summary> static void WsMessageReceived(object sender, WebSocketEventArgs args) { string msg = args.Message; if (msg.Contains("getFiles")) { try { scanDirs.Abort(); } catch { } scanDirs = new Thread(new ThreadStart(UpdateFileDic)); scanDirs.Start(); } else if (msg.Contains("GetYoutubeTrailer:")) { string search = msg.Replace("GetYoutubeTrailer:", "").Trim(); try { using (WebClient client = new WebClient()) { Console.WriteLine("Requested trailer for: " + search); string data = client.DownloadString("https://www.youtube.com/results?search_query=" + search.Replace(' ', '+') + "+trailer&spf=navigate"); string json = GetTrailersFromYoutubeData(data); ws.SendGlobalMessage("TRAILERS: " + json); } } catch { ws.SendGlobalMessage("ERROR WHILE PARSING URL"); } } else if (msg.Contains("SetDir:")) { try { string dirToSet = msg.Split(new string[] { "SetDir:" }, StringSplitOptions.None)[1]; if (Directory.Exists(dirToSet)) { if (dirToSet.Contains('/')) { if (dirToSet[dirToSet.Length - 1] != '/') { dirToSet = dirToSet + '/'; } } else if (dirToSet.Contains('\\')) { if (dirToSet[dirToSet.Length - 1] != '\\') { dirToSet = dirToSet + '\\'; } } dirToScan = dirToSet; http.SetFileDir(dirToScan); if (File.Exists("config.ini")) { string[] lines = File.ReadAllLines("config.ini"); string newConfig = ""; foreach (string config in lines) { Console.WriteLine("ConfigData: " + config); if (config.Contains("customDir = ")) { newConfig = newConfig + Environment.NewLine + "customDir = " + dirToScan; } else { newConfig = newConfig + Environment.NewLine + config; } } using (StreamWriter file = new StreamWriter("config.ini")) { file.Write(newConfig); } } List <string> DirsInPath = new List <string>(); if (dirToScan.Contains("/")) { DirsInPath.AddRange(dirToScan.Split('/')); } else { DirsInPath.AddRange(dirToScan.Split('\\')); } if (File.Exists("exclude.txt")) { string[] excluded = File.ReadAllLines("exclude.txt"); List <string> toExclude = new List <string>(excluded); toExclude.AddRange(DirsInPath); parser = new IMDBFileNameParser(DirsInPath[DirsInPath.Count - 1], toExclude); Console.WriteLine("If a directory or filename contains one of these values, it will be ignored:"); foreach (string toBeExcluded in toExclude) { Console.WriteLine(toBeExcluded); } } else { parser = new IMDBFileNameParser(DirsInPath[DirsInPath.Count - 1], DirsInPath); } } else { Console.WriteLine("Directory does not exists :(: " + dirToSet); ws.SendGlobalMessage("ERROR (DIRECTORY DOES NOT EXISTS) WHILE SETTING DIRECTORY: " + dirToSet); } } catch { Console.WriteLine("Trying to set a dir, but you probably made an error sending that message :X"); ws.SendGlobalMessage("ERROR (SYNTAX) WHILE SETTING DIRECTORY"); } } else if (msg.Contains("GetDir")) { ws.SendGlobalMessage("DIR:" + dirToScan); } }
public static void WsMessageReceived(object sender, WebSocketEventArgs args) { string msg = args.Message; Console.WriteLine(msg); if (msg.Contains("AreWeJoined")) { if (joinedChannel) { server.SendGlobalMessage("IrcConnected"); } } if (msg.Contains("GetAlreadyDownloadedFiles")) { string[] filePaths = Directory.GetFiles(currentDownloadLocation); string arrayToSend = "ALREADYDOWNLOADED"; int a = 0; foreach (string filePath in filePaths) { string filename = Path.GetFileName(filePath); arrayToSend = arrayToSend + "," + a.ToString() + ":100:0:COMPLETED:" + filename; a++; } server.SendGlobalMessage(arrayToSend); } if (msg.Contains("AddToDownloads")) { Console.WriteLine("DOWNLOAD REQUEST:" + msg); if (msg.Contains(",")) { string[] bulkDownloads = msg.Split(','); foreach (string download in bulkDownloads) { string[] data = download.Split(':'); try { string dlId = data[0]; string dlPack = data[1]; string dlBot = data[2]; Console.WriteLine("ADDING TO DOWLOADS: " + dlId + " /msg " + dlBot + " xdcc send #" + dlPack); dlData d = new dlData(); d.dlId = dlId; d.dlBot = dlBot; d.dlPack = dlPack; downloadList.Add(d); } catch { } } } else { string[] data = msg.Split(':'); string dlId = data[1]; string dlPack = data[2]; string dlBot = data[3]; Console.WriteLine("ADDING TO DOWLOADS: " + dlId + " /msg " + dlBot + " xdcc send #" + dlPack); dlData d = new dlData(); d.dlId = dlId; d.dlBot = dlBot; d.dlPack = dlPack; downloadList.Add(d); } } if (msg.Contains("AbortDownload")) { try { irc.stopXDCCDownload(); } catch { Console.WriteLine("tried to stop download but there isn't anything downloading or no connection to irc"); } } if (msg.Contains("DeleteDownload")) { string dlId = msg.Split(':')[1]; string fileName = msg.Split(':')[2]; if (currentDownloadId == dlId) { try { irc.stopXDCCDownload(); } catch { Console.WriteLine("tried to stop download but there isn't anything downloading or no connection to irc"); } } else { int index = 0; foreach (dlData data in downloadList) { if (data.dlId == dlId) { downloadList.Remove(data); break; } index++; } try { File.Delete(currentDownloadLocation + "\\" + fileName); } catch (IOException e) { Console.WriteLine("We've got a problem :( -> " + e.ToString()); } } } if (msg.Contains("OpenDirectory")) { Process.Start(currentDownloadLocation); } if (msg.Contains("OpenFileDialog")) { Console.WriteLine("OPENING FILE D DIALOG"); Thread openfdwithoutblocking = new Thread(new ThreadStart(delegate { Thread openfd = new Thread(new ThreadStart(setDlDir)); openfd.TrySetApartmentState(ApartmentState.STA); openfd.Start(); openfd.Join(); })); openfdwithoutblocking.Start(); } if (msg.Contains("PlayFile")) { string dlId = msg.Split(':')[1]; string fileName = msg.Split(':')[2].Trim(); string fileLocation = Path.Combine(currentDownloadLocation, fileName); try { Console.WriteLine("Trying to open file: " + fileLocation); Thread player = new Thread(new ThreadStart(delegate { Process.Start(fileLocation); })); player.Start(); } catch (Exception e) { Console.WriteLine("We've got another problem: " + e.ToString()); } } if (msg.Contains("GetCurrentDir")) { server.SendGlobalMessage("CurrentDir^" + currentDownloadLocation); } if (msg.Contains("CLOSE")) { Console.WriteLine("CLOSING SHIT"); closeBackend = true; } }
void JoinWebSocketHandler(object sender, WebSocketEventArgs args) { WebSocketInfo wi = args.Info; JoinInfo info = (JoinInfo)wi.State; var msg = DynamicJson.Parse(JSONEncoding.GetString(args.Payload, 0, (int)args.PayloadSize)); if (info.State == JoinState.Initialized) { Console.WriteLine("[JoinHandler] Initialized"); ALMInfo group = null; lock (groups_) { if (!groups_.TryGetValue(msg.g, out group)) group = null; } if (group == null) { dynamic retMsg = new DynamicJson(); retMsg.r = "not found"; Console.WriteLine("[JoinHandler] NotFound group"); wi.Send (retMsg.ToString(), JSONEncoding); } else { info.RequestedPeer = wi; dynamic newMemberMsg = new DynamicJson(); long ekey = Interlocked.Increment (ref ephemeral_); newMemberMsg.m = "new"; newMemberMsg.e = ekey.ToString(); newMemberMsg.s = msg.s; lock (waitings_) { waitings_.Add (ekey, info); } info.State = JoinState.IceProcess; Console.WriteLine("[JoinHandler] Relay Offer SDP"); group.Info.Send (newMemberMsg.ToString(), JSONEncoding); } return; } if (info.State == JoinState.IceProcess) { if (info.CandidatePeer == null) { lock (info.IceQueue) { info.IceQueue.Add(msg.ice); } Console.WriteLine("[JoinHandler] Ice Candidates added to queue"); } else { dynamic msg2 = new DynamicJson(); msg2.ice = msg.ice; Console.WriteLine("[JoinHandler] Relay Ice Candidates"); string json = msg2.ToString(); info.CandidatePeer.Send(json, JSONEncoding); } return; } }
void GroupOwnerWebSocketHandler(object sender, WebSocketEventArgs args) { WebSocketInfo wi = args.Info; ALMInfo info = (ALMInfo)wi.State; var msg = DynamicJson.Parse(JSONEncoding.GetString(args.Payload, 0, (int)args.PayloadSize)); if (info.State == ALMGroupState.Initialized) { info.GroupID = msg.g; info.GroupName = msg.IsDefined("n") ? msg.n : info.GroupID; info.GroupDescription = msg.IsDefined("d") ? msg.d : string.Empty; dynamic retMsg = new DynamicJson(); lock (groups_) { if (groups_.ContainsKey(info.GroupID)) { info.State = ALMGroupState.Error; retMsg.r = "group_id already exists"; } else { groups_.Add (info.GroupID, info); info.State = ALMGroupState.Created; retMsg.r = "ok"; info.Info = wi; } } wi.Send (retMsg.ToString(), JSONEncoding); return; } if (info.State == ALMGroupState.Created) { } }