Repository: slash-hq/slash Branch: master Commit: 01e55ce89b90 Files: 42 Total size: 206.2 KB Directory structure: gitextract_itntp5kx/ ├── .gitignore ├── GitHub/ │ ├── scr.pxm │ ├── slash_logo.pxm │ └── slash_logo_small.pxm ├── LICENSE ├── Package.swift ├── README.md ├── Sources/ │ ├── Application.swift │ ├── ChannelsListView.swift │ ├── CrashReporter.swift │ ├── MessagesListView.swift │ ├── R.swift │ ├── Server.swift │ ├── SlackAdapter.swift │ ├── SlackChannel.swift │ ├── SlackContext.swift │ ├── SlackEmojiDecoder.swift │ ├── SlackEvent.swift │ ├── SlackGroup.swift │ ├── SlackIM.swift │ ├── SlackMessage.swift │ ├── SlackMessageReaction.swift │ ├── SlackOAuth2.swift │ ├── SlackRealTimeClient.swift │ ├── SlackTeam.swift │ ├── SlackUser.swift │ ├── SlackWebClient.swift │ ├── Socket.swift │ ├── TLSSocket.swift │ ├── TerminalCanvas.swift │ ├── TerminalDevice.swift │ ├── TextLayout.swift │ ├── URLSession.swift │ ├── UserInputView.swift │ ├── Utils.swift │ ├── WebSocketClient.swift │ └── main.swift ├── slash.rb ├── slash.sublime-project └── slash.xcodeproj/ ├── project.pbxproj ├── project.xcworkspace/ │ └── contents.xcworkspacedata └── xcshareddata/ └── xcschemes/ └── slash.xcscheme ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ ## Build generated build/ DerivedData/ ## Various settings *.pbxuser !default.pbxuser *.mode1v3 !default.mode1v3 *.mode2v3 !default.mode2v3 *.perspectivev3 !default.perspectivev3 xcuserdata/ ## Other *.moved-aside *.xcuserstate ## Obj-C/Swift specific *.hmap *.ipa *.dSYM.zip *.dSYM ## Playgrounds timeline.xctimeline playground.xcworkspace # Swift Package Manager # # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ .build/ ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: Package.swift ================================================ // swift-tools-version:4.2 import PackageDescription let package = Package( name: "slash", products: [.executable(name: "slash", targets: ["slash"])], targets: [.target(name: "slash", path: "Sources")] ) ================================================ FILE: README.md ================================================ logo Slack terminal client.
![screenshot](GitHub/scr.png) ## Getting started To use `slash` install it via: `brew install https://raw.githubusercontent.com/slash-hq/slash/master/slash.rb` and start it by running: ``` slash ``` Slash can be used with the [development token](https://api.slack.com/docs/oauth-test-tokens) too: ``` slash ``` ## Keys ``` Enter : Send a message Tab : Switch channel Up/Down: Scroll messages Ctrl-C : Quit ``` ## Commands ``` /openurl : open url with ``` logo ## Retro mode Thanks too [cool-retro-term](https://github.com/Swordfish90/cool-retro-term) project slash can run in retro mode ![screenshot](GitHub/scr_retro.png) ## Issues Please make sure to read the Issue Reporting Checklist before opening an issue. Issues not conforming to the guidelines may be closed immediately. ## How to contribute? 1. Fork this repository and clone to your Mac. 1. Open `slash.xcodeproj` in Xcode 1. Build 1. Open `Terminal` and run `/Build/Products/Debug/slash` 1. Make your changes, test and submit pull request! ## FAQ 1. Can I connect to multiple Slack teams? Yes, simply start multiple `slash` instances and login to a different team in each of them. ## License Apache License, Version 2.0 ================================================ FILE: Sources/Application.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation class Application { private let terminalDevice : TerminalDevice private let messagesListView : MessagesListView private let userInputView : UserInputView private let channelsListView : ChannelsListView private let webClient : SlackWebClient private let context : SlackContext private let rtmClient : SlackRealTimeClient private var messages = Array() private var links = [String]() private var selectedChannel: String? = nil private var replyIdCounter = 0 private var unreadChannelsIds = Set() private let adapter = SlackAdapter() init(usingDevice device: TerminalDevice, authenticatedBy token: String) throws { self.terminalDevice = device self.messagesListView = MessagesListView(self.terminalDevice) self.channelsListView = ChannelsListView(self.terminalDevice) self.userInputView = UserInputView(self.terminalDevice) self.webClient = SlackWebClient(authenticatedBy: token) self.terminalDevice.flush( TerminalCanvas() .hideCursor() .color(R.color.connectingTextColor) .cursor(1, 1) .text(R.string.connecting).buffer) let team = try self.webClient.rtm() self.rtmClient = try SlackRealTimeClient(team.wssUrl) self.context = SlackContext(withTeam: team) if let defaultChannel = self.context.defaultChannel { self.selectedChannel = defaultChannel let defaultChannelName = self.context.name(forId: defaultChannel) ?? "" self.userInputView.placeholder = String(format: R.string.inputPlaceholder, defaultChannelName) self.userInputView.draw() self.reloadChannel(defaultChannel, clearChat: false) } DispatchQueue.global(qos: .background).async { [unowned self] in while true { do { while true { if let event = try self.rtmClient.waitForEvent() { self.handleRealTimeSessionEvent(event) } } } catch { self.appendRow(MessagesListRow(spans: [TextSpan(String(format: R.string.connectionError, "\(error)"))])) } } } } func handleRealTimeSessionEvent(_ event: SlackEvent) { switch event { case .hello: self.appendRow(MessagesListRow(spans: [TextSpan(String(format: R.string.hello, self.context.teamName), withColor: R.color.helloTextColor)])) case .reply(let replyId, let ts): if let index = self.messages.index(where: { $0.id == "pending\(replyId)" }) { let old = self.messages.remove(at: index) var newSpans = [TextSpan]() newSpans.append(TextSpan(adapter.formatSlackTimestamp("\(Date().timeIntervalSince1970)") + " ", withColor: R.color.messageTimeTextColor)) newSpans.append(contentsOf: old.spans) self.messages.insert(MessagesListRow(channel: old.channel, id: ts, spans: newSpans), at: index) self.messagesListView.draw(self.messages) } case .message(let message): if let selectedChannel = self.selectedChannel { if message.channel == selectedChannel { self.appendRow(self.messageListRowFor(message: message)) } else { self.unreadChannelsIds.insert(message.channel) self.channelsListView.draw(self.context, selectionId: self.selectedChannel, unreadIds: self.unreadChannelsIds) } } case .messageChanged(let message): if let index = self.messages.index(where: { $0.id == message.ts && $0.channel == message.channel }) { self.messages[index] = self.messageListRowFor(message: message) self.messagesListView.draw(messages) } case .messageDeleted(let ts, let channel): if let index = self.messages.index(where: { $0.id == ts && $0.channel == channel }) { self.messages.remove(at: index) self.messagesListView.draw(self.messages) } case .presenceChange(let user, let presence): if let index = self.context.users.index(where: { $0.id == user }) { let old = self.context.users.remove(at: index) self.context.users.insert(SlackUser(id: old.id, name: old.name, color: old.color, presence: presence), at: index) self.channelsListView.draw(self.context, selectionId: self.selectedChannel, unreadIds: self.unreadChannelsIds) } case .teamRename(let newName): self.context.teamName = newName self.channelsListView.draw(self.context, selectionId: self.selectedChannel, unreadIds: self.unreadChannelsIds) case .desktopNotification(let title, let message): #if os(Linux) // Linux notifications not implemented yet #else Process.launchedProcess(launchPath: "/usr/bin/osascript", arguments: ["-e", "display notification \"\(message)\" with title \"slash: \(title)\""]) #endif return case .messageReactionAdded(let reaction, let channel, let ts): if channel == self.selectedChannel { self.messagesListView.draw(self.messages) } case .unknown(let message): return self.appendRow(MessagesListRow(spans: ["?", " : ", TextSpan(message)])) default: break } } func notifyTerminalSizeHasChanged() { self.messagesListView.draw(self.messages) self.channelsListView.draw(self.context, selectionId: self.selectedChannel) self.userInputView.draw() } private func messageListRowFor(message: SlackMessage) -> MessagesListRow { let spans = self.adapter.textSpansFor(message: message, withContext: self.context, andLinks: &self.links) return MessagesListRow(channel: message.channel, id: message.ts, spans: spans) } func appendRow(_ row: MessagesListRow) { self.messages.insert(row, at: 0) self.messagesListView.draw(messages) } func reloadChannel(_ channelId: String, clearChat: Bool = true) { let loadingRow = MessagesListRow(spans: [TextSpan(R.string.loading, withColor: R.color.loadingTextColor)]) if clearChat { self.messagesListView.draw([loadingRow]) } else { self.messages.append(loadingRow) self.messagesListView.draw(self.messages) } DispatchQueue.global(qos: .background).async { [unowned self] in do { let rows = try self.webClient.history(for: channelId).map { self.messageListRowFor(message: $0) } //TODO notify about the results in a common queue for all the background tasks. self.messages.removeAll(keepingCapacity: true) self.messages.append(contentsOf: rows) self.messagesListView.draw(self.messages) self.channelsListView.draw(self.context, selectionId: self.selectedChannel, unreadIds: self.unreadChannelsIds) self.userInputView.draw() } catch { //TODO handle error case. } } } func run() { self.messagesListView.draw(self.messages) while true { let key = self.terminalDevice.key() switch key { case .ctrlC: try? self.terminalDevice.reset() exit(1) case .enter: guard !self.userInputView.input.isEmpty, let targetChannel = self.selectedChannel, let me = self.context.me else { continue } let message = self.userInputView.input if !self.executeLocalCommand(message) { try? self.rtmClient.send(targetChannel, message: message, replyId: replyIdCounter) let pendingMessage = MessagesListRow(channel: targetChannel, id: "pending\(replyIdCounter)", spans: [ TextSpan(me.name, withColor: Utils.xterm256Color(forUser: me)), TextSpan(": ", withColor: R.color.messagePrefixTextColor), TextSpan(message, withColor: R.color.messageTextColor)], pending: true) self.messages.insert(pendingMessage, at: 0) self.replyIdCounter = self.replyIdCounter + 1 self.messagesListView.draw(self.messages) } self.userInputView.input = "" self.userInputView.cursor = 0 self.userInputView.draw() case .backspace: if self.userInputView.input.isEmpty || self.userInputView.cursor <= 0 { continue } self.userInputView.input.remove(at: userInputView.input.index(self.userInputView.input.startIndex, offsetBy: self.userInputView.cursor-1)) self.userInputView.cursor = max(0, self.userInputView.cursor - 1) self.userInputView.draw() case .arrowLeft: self.userInputView.cursor = max(0, userInputView.cursor - 1) self.userInputView.draw() case .arrowRight: self.userInputView.cursor = min(userInputView.input.count, userInputView.cursor + 1) self.userInputView.draw() case .arrowUp: self.messagesListView.scroll = self.messagesListView.scroll + 1 self.messagesListView.draw(self.messages) case .arrowDown: guard self.messagesListView.scroll > 0 else { break } self.messagesListView.scroll = self.messagesListView.scroll - 1 self.messagesListView.draw(self.messages) case .tab(let withShift): guard let suggestion = self.context.suggestRecipient(for: self.selectedChannel, unreadIds: self.unreadChannelsIds, backwardSearch: withShift) else { continue } self.userInputView.input = "" self.userInputView.cursor = 0 self.messagesListView.scroll = 0 self.unreadChannelsIds.remove(suggestion.id) self.selectedChannel = suggestion.id self.userInputView.placeholder = String(format: R.string.inputPlaceholder, suggestion.name) self.channelsListView.draw(self.context, selectionId: suggestion.id, unreadIds: self.unreadChannelsIds) self.reloadChannel(suggestion.id) self.links.removeAll() self.userInputView.draw() case .other(let character): self.userInputView.input.insert(character, at: self.userInputView.input.index(self.userInputView.input.startIndex, offsetBy: self.userInputView.cursor)) self.userInputView.cursor = userInputView.cursor + 1 self.userInputView.draw() default: break } } } /// Execute a local "slash" command. /// /// The currently supported list of local commands are; /// /// - /openurl {space separated list of numbers}: opens numbered link in default browser /// func executeLocalCommand(_ command: String) -> Bool { if (command.hasPrefix("/openurl")) { let pieces = command.components(separatedBy: [",", " "]) let linkNumbers = pieces.compactMap { Int($0) } for linkNumber in linkNumbers { let url = self.links[linkNumber - 1] Utils.shell("open", url) } return true } return false } } ================================================ FILE: Sources/ChannelsListView.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation struct ChannelListRow { let id: String let name: String } class ChannelsListView { private let canvas = TerminalCanvas() private let terminalDevice: TerminalDevice init(_ device: TerminalDevice) { self.terminalDevice = device } func drawRow(_ text: String, row: Int, highlight: Bool = false, blink: Bool = false) { let availableWidth = R.dimen.channelsListWidth let paddedName = text.count > availableWidth ? String(text[.. = []) { let size = self.terminalDevice.size let avaibleHeight = size.height guard size.width > 0 && avaibleHeight > 0 else { return } var offset = 1 self.canvas .clear() .hideCursor() // Draw team name. self.canvas .color(R.color.teamNameTextColor) .background(R.color.teamNameBackgroundColor) .cursor(1, 1) .text(context.teamName.padding(toLength: R.dimen.channelsListWidth, withPad: " ", startingAt: 0)) offset = offset + 1 // Draw channels. self.canvas.color(R.color.channelNameTextColor); for channel in context.channels { if (!channel.isMember) { continue } self.drawRow("#" + channel.name, row: offset, highlight: channel.id == selectionId, blink: unreadIds.contains(channel.id)) offset = offset + 1 if offset > avaibleHeight { break } } // Draw groups. self.canvas.color(R.color.groupNameTextColor); if offset < avaibleHeight { for group in context.groups { self.drawRow("#" + group.name, row: offset, highlight: group.id == selectionId, blink: unreadIds.contains(group.id)) offset = offset + 1 if offset > avaibleHeight { break } } } // Draw members. if offset < avaibleHeight { for im in context.ims { let slackUser = context.user(forId: im.user) ?? SlackUser(id: "", name: "", color: "", presence: .away) if slackUser.presence == .active { self.canvas.color(Utils.xterm256Color(forUser: slackUser)) } else { self.canvas.color(R.color.channelListTextColorAway) } self.drawRow("@" + (context.user(forId: im.user)?.name ?? ""), row: offset, highlight: im.id == selectionId, blink: unreadIds.contains(im.id)) offset = offset + 1 if offset > avaibleHeight { break } } } self.canvas .color(R.color.channelNameTextColor) .background(R.color.channelListBgColor) while offset <= avaibleHeight { self.canvas .cursor(1, offset) .text(String(repeating: " ", count: R.dimen.channelsListWidth)) offset = offset + 1 } self.canvas.reset() terminalDevice.flush(self.canvas.buffer) } } ================================================ FILE: Sources/CrashReporter.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation struct CrashReporter { private static var terminalDevice: TerminalDevice? = nil static func watch(usingDevice device: TerminalDevice) { CrashReporter.terminalDevice = device NSSetUncaughtExceptionHandler { _ in CrashReporter.report() } signal(SIGABRT) { _ in CrashReporter.report() } signal(SIGILL) { _ in CrashReporter.report() } signal(SIGSEGV) { _ in CrashReporter.report() } signal(SIGFPE) { _ in CrashReporter.report() } signal(SIGBUS) { _ in CrashReporter.report() } signal(SIGPIPE) { _ in CrashReporter.report() } } private static func report() { try? CrashReporter.terminalDevice?.reset() let stacktrace = Thread.callStackSymbols.joined(separator: "\n") let title = "Crash detected".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "" let body = ("I found the following crash in the app:\n```" + stacktrace + "```") .addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "" CrashReporter.terminalDevice?.flush(TerminalCanvas() .reset() .clear() .text("Oooops.... we are really sorry but slash has crashed ☠️ :\n\nSTACKTRACE:\n\n") .text(stacktrace) .text("\n\n") .text("Please copy this very long link to the browser, to help us with fixing the crash 🙇 \n\nhttps://github.com/slash-hq/slash/issues/new?title=\(title)&body=\(body))\n\n") .text("Thank you, \nslash Team\n\n") .buffer) exit(1) } } ================================================ FILE: Sources/MessagesListView.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation struct MessagesListRow { let channel: String? let id: String? let spans: [TextSpan] let pending: Bool init(channel: String? = nil, id: String? = nil, spans: [TextSpan], pending: Bool = false) { self.channel = channel self.id = id self.spans = spans self.pending = pending } } class MessagesListView { private let canvas = TerminalCanvas() private let textLayout = TextLayout() private let terminalDevice: TerminalDevice init(_ device: TerminalDevice) { self.terminalDevice = device } var scroll = 0 func draw(_ rows: Array) { let size = self.terminalDevice.size let bottomPadding = 2 guard size.width > 0 && size.height > bottomPadding else { return } let avaibleHeight = size.height - bottomPadding self.canvas .clear() .hideCursor() let column = R.dimen.channelsListWidth + 2 var rayOffset = avaibleHeight var scrollOffset = self.scroll // Draw from the bottom to the top. lines: for row in rows { let lines = self.textLayout.layout(row.spans, alignToWidth: size.width - column - 1) for line in lines.reversed() { if scrollOffset > 0 { scrollOffset = scrollOffset - 1 continue } self.canvas .cursor(column-1, rayOffset) .background(R.color.messagesListBgColor) .text(" ") .buffer.append(contentsOf: line) rayOffset = rayOffset - 1 if rayOffset < 1 { break lines } } } // Clear the top if needed. if rayOffset > 0 { for i in 1...rayOffset { self.canvas .cursor(R.dimen.channelsListWidth + 1, i) .color(R.color.defaulTextColor) .background(R.color.messagesListBgColor) .text(String(repeating: " ", count: size.width - R.dimen.channelsListWidth)) } } self.canvas.reset() terminalDevice.flush(self.canvas.buffer) } } ================================================ FILE: Sources/R.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation class R { class string { // Cool emojis: 🚫❕❗️📢📣🚀🐌🌊💦🌪❄️💥💡🗑⏱🔪💉🌡🚿🎈🎁🏷🔖🔐🔒🔓🔏⚠️💩 static let inputPlaceholder = "Message #%@..." static let unknownMessageAuthor = "(unknown)" static let directMessageAuthor = "private" static let hello = "Connected to %@ team." static let unknownMessageChannel = "??" static let connecting = "Connecting 💤 ..." static let loading = "Loading 💤 ..." static let connectionError = "⚠️ Connection error occured (%@)" static let me = "me" static let authHelpMessage = "🔒 Visit ( %@ ) to login using OAuth2..." static let authConfirmation = "
" + "


" + "

You can close this window now and continue in the terminal.


" + "" + "
" } class color { // XTERM-256 palette: https://jonasjacek.github.io/colors/ static let defaultBgColor = -1 static let defaulTextColor = -1 static let connectingTextColor = 255 static let helloTextColor = 255 static let commandTextColor = 201 static let userInputTextColor = 231 static let userInputBackgorundColor = 16 static let userInputPlaceholderTextColor = 242 static let userInputSeparatorTextColor = 255 static let messageAuthorTextColor = 158 static let messagePrefixTextColor = 104 static let messageTextColor = 252 static let messageTimeTextColor = 24 static let messageHighlightedBgColor = 154 static let teamNameTextColor = 15 static let teamNameBackgroundColor = 234 static let channelNameTextColor = 38 static let groupNameTextColor = 190 static let directMessageTextColor = 240 static let channelListTextColorAway = 239 static let channelListBgColor = 232 static let channelListBgColorSelected = 15 static let channelListBgColorNotRead = 148 static let messagesListBgColor = 0 static let loadingTextColor = 11 static let linkTextColor = 11 static let mentionTextColor = 37 static let reactionTextColor = 15 } class dimen { static let channelsListWidth = 17 } } ================================================ FILE: Sources/Server.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation class Request { enum HttpVersion { case http10, http11 } var httpVersion = HttpVersion.http10 var method = "" var path = "" var query = [(String, String)]() var headers = [(String, String)]() var body = [UInt8]() var contentLength = 0 func hasToken(_ token: String, forHeader headerName: String) -> Bool { guard let (_, value) = headers.filter({ $0.0 == headerName }).first else { return false } return value .components(separatedBy: ",") .filter({ $0.trimmingCharacters(in: .whitespaces).lowercased() == token }) .count > 0 } } class Response { init() { } init(_ status: Status = Status.ok) { self.status = status.rawValue } init(_ status: Int = Status.ok.rawValue) { self.status = status } init(_ body: Array) { self.body.append(contentsOf: body) } init(_ body: ArraySlice) { self.body.append(contentsOf: body) } var status = Status.ok.rawValue var headers = [(String, String)]() var body = [UInt8]() var processingSuccesor: IncomingDataProcessor? = nil } class TextResponse: Response { init(_ status: Int = Status.ok.rawValue, _ text: String) { super.init(status) self.headers.append(("Content-Type", "text/plain")) self.body = [UInt8](text.utf8) } } class HtmlResponse: Response { init(_ status: Int = Status.ok.rawValue, _ text: String) { super.init(status) self.headers.append(("Content-Type", "text/html")) self.body = [UInt8](text.utf8) } } enum Status: Int { case `continue` = 100 case switchingProtocols = 101 case ok = 200 case created = 201 case accepted = 202 case noContent = 204 case resetContent = 205 case partialContent = 206 case movedPerm = 301 case notModified = 304 case badRequest = 400 case unauthorized = 401 case forbidden = 403 case notFound = 404 } extension UInt8 { static var lf: UInt8 = 10, cr: UInt8 = 13, space: UInt8 = 32, colon: UInt8 = 58, ampersand: UInt8 = 38, lessThan: UInt8 = 60, greaterThan: UInt8 = 62, slash: UInt8 = 47, equal: UInt8 = 61, doubleQuotes: UInt8 = 34, openingParenthesis: UInt8 = 40, closingParenthesis: UInt8 = 41, comma: UInt8 = 44 } enum AsyncError: Error { case parse(String) case async(String) case socketCreation(String) case setReUseAddr(String) case setNoSigPipeFailed(String) case setNonBlockFailed(String) case setReuseAddrFailed(String) case bindFailed(String) case listenFailed(String) case writeFailed(String) case getPeerNameFailed(String) case convertingPeerNameFailed case getNameInfoFailed(String) case acceptFailed(String) case readFailed(String) case httpError(String) } protocol TcpServer { init(_ port: in_port_t) throws func wait(_ callback: ((TcpServerEvent) -> Void)) throws func write(_ socket: Int32, _ data: Array, _ done: @escaping (() -> TcpWriteDoneAction)) throws func finish(_ socket: Int32) } enum TcpWriteDoneAction { case `continue` case terminate } enum TcpServerEvent { case connect(String, Int32) case disconnect(String, Int32) case data(String, Int32, ArraySlice) } class HttpIncomingDataPorcessor: Hashable, IncomingDataProcessor { private enum State { case waitingForHeaders case waitingForBody } private var state = State.waitingForHeaders private let socket: Int32 private var buffer = Array() private var request = Request() private let callback: ((Request) throws -> Void) init(_ socket: Int32, _ closure: @escaping ((Request) throws -> Void)) { self.socket = socket self.callback = closure } static func == (lhs: HttpIncomingDataPorcessor, rhs: HttpIncomingDataPorcessor) -> Bool { return lhs.socket == rhs.socket } var hashValue: Int { return Int(self.socket) } func process(_ chunk: ArraySlice) throws { switch self.state { case .waitingForHeaders: guard self.buffer.count + chunk.count < 4096 else { throw AsyncError.parse("Headers size exceeds that limit.") } var iterator = chunk.makeIterator() while let byte = iterator.next() { if byte != UInt8.cr { buffer.append(byte) } if buffer.count >= 2 && buffer[buffer.count-1] == UInt8.lf && buffer[buffer.count-2] == UInt8.lf { self.buffer.removeLast(2) self.request = try self.consumeHeader(buffer) self.buffer.removeAll(keepingCapacity: true) let left = [UInt8](iterator) self.state = .waitingForBody try self.process(left[0.. Request { let lines = data.split(separator: UInt8.lf) guard let requestLine = lines.first else { throw AsyncError.httpError("No status line.") } let requestLineTokens = requestLine.split(separator: UInt8.space) guard requestLineTokens.count >= 3 else { throw AsyncError.httpError("Invalid status line.") } let request = Request() if requestLineTokens[2] == [0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x30] { request.httpVersion = .http10 } else if requestLineTokens[2] == [0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31] { request.httpVersion = .http11 } else { throw AsyncError.parse("Invalid http version: \(requestLineTokens[2])") } request.headers = lines .dropFirst() .map { line in let headerTokens = line.split(separator: UInt8.colon, maxSplits: 1) if let name = headerTokens.first, let value = headerTokens.last { if let nameString = String(bytes: name, encoding: .ascii), let valueString = String(bytes: value, encoding: .ascii) { return (nameString.lowercased(), valueString.trimmingCharacters(in: .whitespaces)) } } return ("", "") } if let (_, value) = request.headers .filter({ $0.0 == "content-length" }) .first { guard let contentLength = Int(value) else { throw AsyncError.parse("Invalid 'Content-Length' header value \(value).") } request.contentLength = contentLength } guard let method = String(bytes: requestLineTokens[0], encoding: .ascii) else { throw AsyncError.parse("Invalid 'method' value \(requestLineTokens[0]).") } request.method = method guard let path = String(bytes: requestLineTokens[1], encoding: .ascii) else { throw AsyncError.parse("Invalid 'path' value \(requestLineTokens[1]).") } let queryComponents = path.components(separatedBy: "?") if queryComponents.count > 1, let first = queryComponents.first, let last = queryComponents.last { request.path = first request.query = last .components(separatedBy: "&") .reduce([(String, String)]()) { (c, s) -> [(String, String)] in let tokens = s.components(separatedBy: "=") if let name = tokens.first, let value = tokens.last { if let nameDecoded = name.removingPercentEncoding, let valueDecoded = value.removingPercentEncoding { return c + [(nameDecoded, tokens.count > 1 ? valueDecoded : "")] } } return c } } else { request.path = path } return request } } class Server { private var processors = [Int32 : IncomingDataProcessor]() private let server: TcpServer init(_ port: in_port_t = 8080) throws { #if os(Linux) self.server = try LinuxAsyncServer(port) #else self.server = try MacOSAsyncTCPServer(port) #endif } func serve(_ callback: @escaping ((request: Request, responder: ((Response) -> Void))) -> Void) throws { try self.server.wait { event in switch event { case .connect(_, let socket): self.processors[socket] = HttpIncomingDataPorcessor(socket) { request in callback((request, { response in let keepIOSession = self.supportsKeepAlive(request.headers) || request.httpVersion == .http11 var data = [UInt8]() data.reserveCapacity(1024) data.append(contentsOf: [UInt8]("HTTP/\(request.httpVersion == .http10 ? "1.0" : "1.1") \(response.status) OK\r\n".utf8)) for (name, value) in response.headers { data.append(contentsOf: [UInt8]("\(name): \(value)\r\n".utf8)) } if (keepIOSession) { data.append(contentsOf: [UInt8]("Connection: keep-alive\r\n".utf8)) } data.append(contentsOf: [UInt8]("Content-Length: \(response.body.count)\r\n".utf8)) data.append(contentsOf: [13, 10]) data.append(contentsOf: response.body) do { try self.server.write(socket, data) { if let sucessor = response.processingSuccesor { self.processors[socket] = sucessor return .continue } return keepIOSession ? .continue : .terminate } } catch { self.processors.removeValue(forKey: socket) } })) } case .disconnect(_, let socket): self.processors.removeValue(forKey: socket) case .data(_, let socket, let chunk): do { try self.processors[socket]?.process(chunk) } catch { self.processors.removeValue(forKey: socket) self.server.finish(socket) } } } } private func supportsKeepAlive(_ headers: Array<(String, String)>) -> Bool { if let (_, value) = headers.filter({ $0.0 == "connection" }).first { return "keep-alive" == value.trimmingCharacters(in: CharacterSet.whitespaces) } return false } private func closeConnection(_ headers: Array<(String, String)>) -> Bool { if let (_, value) = headers.filter({ $0.0 == "connection" }).first { return "close" == value.trimmingCharacters(in: CharacterSet.whitespaces) } return false } } protocol IncomingDataProcessor { func process(_ chunk: ArraySlice) throws } extension Process { static var pid: Int { return Int(getpid()) } static var tid: UInt64 { #if os(Linux) return UInt64(pthread_self()) #else var tid: __uint64_t = 0 pthread_threadid_np(nil, &tid); return UInt64(tid) #endif } static var error: String { return String(cString: UnsafePointer(strerror(errno))) } } class MacOSAsyncTCPServer: TcpServer { private var backlog = Dictionary TcpWriteDoneAction))>>() private var peers = Set() private let kernelQueue: KernelQueue private let server: UInt required init(_ port: in_port_t = 8080) throws { self.kernelQueue = try KernelQueue() self.server = UInt(try MacOSAsyncTCPServer.nonBlockingSocketForListenening(port)) self.kernelQueue.subscribe(server, .read) } func write(_ socket: Int32, _ data: Array, _ done: @escaping (() -> TcpWriteDoneAction)) throws { let result = Socket.write(socket, data, data.count) if result == -1 { defer { self.finish(socket) } throw AsyncError.writeFailed(Process.error) } if result == data.count { if done() == .terminate { self.finish(socket) } return } self.backlog[socket]?.append(([UInt8](data[result.. Void)) throws { try self.kernelQueue.wait { signal in switch signal.event { case .read: if signal.ident == self.server { let client = try MacOSAsyncTCPServer.acceptAndConfigureClientSocket(Int32(signal.ident)) self.peers.insert(client) self.backlog[Int32(client)] = [] kernelQueue.subscribe(UInt(client), .read) kernelQueue.subscribe(UInt(client), .write) kernelQueue.pause(UInt(client), .write) callback(.connect("", Int32(client))) } else { var chunk = [UInt8](repeating: 0, count: signal.data) let result = Socket.read(Int32(signal.ident), &chunk, signal.data) if result <= 0 { finish(Int32(signal.ident)) callback(.disconnect("", Int32(signal.ident))) } else { callback(.data("", Int32(signal.ident), chunk[0.. Int32 { let server = Darwin.socket(AF_INET, SOCK_STREAM, 0) guard server != -1 else { throw AsyncError.socketCreation(Process.error) } var value: Int32 = 1 if Darwin.setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &value, socklen_t(MemoryLayout.size)) == -1 { defer { let _ = Socket.close(server) } throw AsyncError.setReuseAddrFailed(Process.error) } try setSocketNonBlocking(server) try setSocketNoSigPipe(server) var addr = anyAddrForPort(port) if withUnsafePointer(to: &addr, { Darwin.bind(server, UnsafePointer(OpaquePointer($0)), socklen_t(MemoryLayout.size)) }) == -1 { defer { let _ = Socket.close(server) } throw AsyncError.bindFailed(Process.error) } if Darwin.listen(server, SOMAXCONN) == -1 { defer { let _ = Socket.close(server) } throw AsyncError.listenFailed(Process.error) } return server } static func acceptAndConfigureClientSocket(_ socket: Int32) throws -> Int32 { guard case let client = Darwin.accept(socket, nil, nil), client != -1 else { throw AsyncError.acceptFailed(Process.error) } try self.setSocketNonBlocking(client) try self.setSocketNoSigPipe(client) return client } static func anyAddrForPort(_ port: in_port_t) -> sockaddr_in { var addr = sockaddr_in() addr.sin_len = __uint8_t(MemoryLayout.size) addr.sin_family = sa_family_t(AF_INET) addr.sin_port = port.bigEndian addr.sin_addr = in_addr(s_addr: in_addr_t(0)) addr.sin_zero = (0, 0, 0, 0, 0, 0, 0, 0) return addr } static func setSocketNonBlocking(_ socket: Int32) throws { if Darwin.fcntl(socket, F_SETFL, Darwin.fcntl(socket, F_GETFL, 0) | O_NONBLOCK) == -1 { throw AsyncError.setNonBlockFailed(Process.error) } } static func setSocketNoSigPipe(_ socket: Int32) throws { var value = 1 if Darwin.setsockopt(socket, SOL_SOCKET, SO_NOSIGPIPE, &value, socklen_t(MemoryLayout.size)) == -1 { throw AsyncError.setNoSigPipeFailed(Process.error) } } } class KernelQueue { private var events = Array(repeating: kevent(), count: 256) private var changes = Array() private let queue: Int32 enum Subscription { case read, write } enum Event { case read, write, error } init() throws { guard case let queue = kqueue(), queue != -1 else { throw AsyncError.async(Process.error) } self.queue = queue } func subscribe(_ ident: UInt, _ event: Subscription) { switch event { case .read : changes.append(self.event(UInt(ident), Int16(EVFILT_READ), UInt16(EV_ADD) | UInt16(EV_ENABLE))) case .write : changes.append(self.event(UInt(ident), Int16(EVFILT_WRITE), UInt16(EV_ADD) | UInt16(EV_ENABLE))) } } func unsubscribe(_ ident: UInt, _ event: Subscription) { switch event { case .read : changes.append(self.event(UInt(ident), Int16(EVFILT_READ), UInt16(EV_DELETE))) case .write : changes.append(self.event(UInt(ident), Int16(EVFILT_WRITE), UInt16(EV_DELETE))) } } func pause(_ ident: UInt, _ event: Subscription) { switch event { case .read : changes.append(self.event(UInt(ident), Int16(EVFILT_READ), UInt16(EV_DISABLE))) case .write : changes.append(self.event(UInt(ident), Int16(EVFILT_WRITE), UInt16(EV_DISABLE))) } } func resume(_ ident: UInt, _ event: Subscription) { switch event { case .read : changes.append(self.event(UInt(ident), Int16(EVFILT_READ), UInt16(EV_ENABLE))) case .write : changes.append(self.event(UInt(ident), Int16(EVFILT_WRITE), UInt16(EV_ENABLE))) } } private func event(_ ident: UInt, _ filter: Int16, _ flags: UInt16) -> kevent { return kevent(ident: ident, filter: filter, flags: flags, fflags: 0, data: 0, udata: nil) } func wait(_ callback: (_ tuple: (event: Event, ident: UInt, data: Int)) throws -> (Void)) throws { if !changes.isEmpty { if kevent(self.queue, &changes, Int32(changes.count), nil, 0, nil) == -1 { throw AsyncError.async(Process.error) } } self.changes.removeAll(keepingCapacity: true) guard case let count = kevent(self.queue, nil, 0, &events, Int32(events.count), nil), count != -1 else { throw AsyncError.async(Process.error) } for event in events[0.. String { if let timestamp = Double(slackTs) { let date = Date(timeIntervalSince1970: timestamp) return self.dateFormatter.string(from: date) } else { return slackTs } } func textSpansFor(message: SlackMessage, withContext context: SlackContext, andLinks links: inout [String]) -> [TextSpan] { let slackUser = context.user(forId: message.user) ?? SlackUser(id: "", name: "unknown", color: "", presence: .away) var spans = [TextSpan]() spans.append(TextSpan(self.formatSlackTimestamp(message.ts), withColor: R.color.messageTimeTextColor)) spans.append(TextSpan(" \(slackUser.name)", withColor: Utils.xterm256Color(forUser: slackUser))) spans.append(TextSpan(": ", withColor: R.color.messagePrefixTextColor)) spans.append(contentsOf: self.spansFor(message: message.text, withContext: context, andLinks: &links)) if !message.reactions.isEmpty { let content = "\n " + message.reactions.map({ emojiDecoder.decode( ":" + $0.name + ":" ) + reactionCounter(forCount: $0.count) } ).joined(separator: " ") spans.append(TextSpan(content, withColor: R.color.reactionTextColor, withBackground: R.color.defaultBgColor)) } return spans } func reactionCounter(forCount count: Int) -> String { if count <= 1 { return "" } return String(String(describing: count).map({ c in //TODO - Do it better with 'U+2080 + x' formula. switch c { case "0": return "₀" case "1": return "₁" case "2": return "₂" case "3": return "₃" case "4": return "₄" case "5": return "₅" case "6": return "₆" case "7": return "₇" case "8": return "₈" case "9": return "₉" default : return " " } })) } func spansFor(message: String, withContext context: SlackContext, andLinks links: inout [String]) -> [TextSpan] { var spans = [TextSpan]() for token in self.lex(for: message) { switch token { case .plain(let text): let presentableText = self.emojiDecoder.decode(self.decodeEscapedHTMLEntities(text)) spans.append(TextSpan(presentableText, withColor: R.color.messageTextColor)) case .escaped(let encodedText): guard let first = encodedText.first else { continue } switch first { case "#": fallthrough case "@": let idStartIndex = encodedText.index(encodedText.startIndex, offsetBy: 1) if idStartIndex < encodedText.endIndex { let id = encodedText[idStartIndex..<(encodedText.index(of: "|") ?? encodedText.endIndex)] if let name = context.name(forId: String(id)) { spans.append(TextSpan(name, withColor: R.color.mentionTextColor)) } } case "!": let escapedTokens = encodedText.components(separatedBy: "|") if let command = escapedTokens.first { let commandName = escapedTokens.count > 1 ? escapedTokens[1] : command spans.append(TextSpan(commandName, withColor: R.color.commandTextColor)) } default /* link */: let escapedTokens = encodedText.components(separatedBy: "|") if let url = escapedTokens.first { links.append(url) if let name = escapedTokens.last, escapedTokens.count > 1 { spans.append(TextSpan(self.decodeEscapedHTMLEntities(name), withColor: R.color.linkTextColor)) } else { spans.append(TextSpan(url, withColor: R.color.linkTextColor)) } spans.append(TextSpan("[" + String(links.count) + "]", withColor: R.color.messageTextColor)) } } } } return spans } enum Token { case plain(String), escaped(String) } private func lex(for message: String) -> [Token] { var tokens = [Token]() var buffer = [Character]() buffer.reserveCapacity(message.count) var plainFlag = true for (index, character) in message.enumerated() { switch character { case "<": if !buffer.isEmpty { tokens.append(.plain(String(buffer))) } buffer.removeAll(keepingCapacity: true) plainFlag = false case ">": if !buffer.isEmpty { tokens.append(.escaped(String(buffer))) } buffer.removeAll(keepingCapacity: true) plainFlag = true default: buffer.append(character) if index == message.count - 1 { tokens.append(plainFlag ? .plain(String(buffer)) : .escaped(String(buffer))) } } } return tokens } private func decodeEscapedHTMLEntities(_ text: String) -> String { return text .replacingOccurrences(of: "&", with: "&") .replacingOccurrences(of: "<", with: "<") .replacingOccurrences(of: ">", with: ">") } } ================================================ FILE: Sources/SlackChannel.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation struct SlackChannel { let id: String let name: String let members: [String] let topic: String let general: Bool let isMember: Bool } ================================================ FILE: Sources/SlackContext.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation class SlackContext { var teamName : String var selfId : String var users = [SlackUser]() var channels = [SlackChannel]() var groups = [SlackGroup]() var ims = [SlackIM]() init(withTeam team: SlackTeam) { self.teamName = team.name self.selfId = team.selfId self.users.append(contentsOf: team.users) self.channels.append(contentsOf: team.channels) self.groups.append(contentsOf: team.groups) self.ims.append(contentsOf: team.ims) } func suggestRecipient(for selection: String?, unreadIds: Set = [], backwardSearch: Bool) -> (id: String, name: String)? { let channels = self.channels.filter({ $0.isMember }).map { ($0.id, $0.name) } let groups = self.groups.map { ($0.id, $0.name) } let ims = self.ims.map { im in (im.id, (self.users.filter({ $0.id == im.user }).first?.name) ?? "") } let candidates = (channels + groups + ims).filter { unreadIds.isEmpty ? true : (unreadIds.contains($0.0) || $0.0 == selection) } var suggestion: (id: String, name: String)? = nil if let current = candidates.index(where: { $0.0 == selection }) { if backwardSearch { let next = current - 1 if next < 0 { suggestion = candidates.last } else { suggestion = candidates[next] } } else { let next = current + 1 if next >= candidates.count { suggestion = candidates.first } else { suggestion = candidates[next] } } } return suggestion } func name(forId id: String) -> String? { var name = self.channels.filter({ $0.id == id }).first?.name if name == nil { name = self.groups.filter({ $0.id == id }).first?.name } if name == nil { if let im = self.ims.filter({ $0.id == id }).first { if let user = self.users.filter({ $0.id == im.user }).first { name = user.name } } } if name == nil { if let user = self.users.filter({ $0.id == id }).first { return user.name } } return name } func user(forId id: String) -> SlackUser? { return self.users.filter({ $0.id == id }).first } var me: SlackUser? { return self.users.filter({ $0.id == self.selfId }).first } var defaultChannel: String? { return self.channels.filter({ $0.general }).first?.id } } ================================================ FILE: Sources/SlackEmojiDecoder.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation class SlackEmojiDecoder { func decode(_ text: String) -> String { //TODO - improve this by iterating only once over the text. return text .replacingOccurrences(of: ":skin-tone-1:", with: "🏻") .replacingOccurrences(of: ":skin-tone-2:", with: "🏻") .replacingOccurrences(of: ":skin-tone-3:", with: "🏼") .replacingOccurrences(of: ":skin-tone-4:", with: "🏽") .replacingOccurrences(of: ":skin-tone-5:", with: "🏾") .replacingOccurrences(of: ":skin-tone-6:", with: "🏿") .replacingOccurrences(of: ":100:", with: "💯") .replacingOccurrences(of: "<3", with: "❤️") .replacingOccurrences(of: " String? { let permissionsStr = self.permissions.joined(separator: " ") Utils.shell("open", "https://slack.com/oauth/authorize?client_id=\(self.clientId)&scope=\(permissionsStr)&redirect_uri=\(SlackOAuth2.address)") let server = try Server(in_port_t(SlackOAuth2.port)) var processIncomingRequests = true while processIncomingRequests { try server.serve { (request, responder) in guard request.path == "/" else { responder(TextResponse(200, "Invalid request.")) return } guard let code = request.query.first?.1 else { responder(TextResponse(200, "Could not get the code.")) return } guard let url = URL(string: "https://slack.com/api/oauth.access?client_id=\(self.clientId)&client_secret=\(self.clientSecret)&code=\(code)&redirect_uri=\(SlackOAuth2.address)") else { responder(TextResponse(200, "Could not create URL object.")) return } do { let (theData, _) = try URLSession.shared.synchronousDataTask(with: URLRequest(url: url)) guard let data = theData else { responder(TextResponse(200, "No response from Slack.")) return } let object = try JSONSerialization.jsonObject(with:data) guard let dict = object as? Dictionary else { responder(TextResponse(200, "Slack's response is not a dictionary \(object).")) return } guard let accessToken = dict["access_token"] as? String else { responder(TextResponse(200, "Could not find access token in the response \(dict).")) return } self.accessToken = accessToken processIncomingRequests = false responder(HtmlResponse(200, R.string.authConfirmation)) } catch { responder(TextResponse(200, "Error occured for token request \(error).")) } } } return self.accessToken } } ================================================ FILE: Sources/SlackRealTimeClient.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation class SlackRealTimeClient { enum Err: Error { case error(String) } private let websocketClient: WebSocketClient init(_ url: String) throws { guard let wssUrl = URL(string: url) else { throw Err.error("Failed to create URL object from: \(url).") } guard let wssHost = wssUrl.host else { throw Err.error("Could not find host for: \(wssUrl).") } self.websocketClient = try WebSocketClient(wssHost, path: wssUrl.path) } func send(_ channel: String, message: String, replyId: Int) throws { let jsonData = try JSONSerialization.data(withJSONObject: ["id": replyId, "type": "message", "channel": channel, "text": message], options: .prettyPrinted) try self.websocketClient.writeFrame(opcode: .text, payload: [UInt8](jsonData)) } func waitForEvent() throws -> SlackEvent? { guard let frame = try self.websocketClient.waitForFrame() else { return nil } switch frame.opcode { case .text: let object = try JSONSerialization.jsonObject(with: Data(frame.payload), options: .init(rawValue: 0)) guard let dictionary = object as? Dictionary else { return nil } if let replyToId = dictionary["reply_to"] as? Int { let ts = (dictionary["ts"] as? String) ?? "" return .reply(replyToId, ts) } guard let type = dictionary["type"] as? String else { return nil } switch type { case "hello": return .hello case "message": return self.handleMessageEvent(dictionary) case "reconnect_url": return .reconnectUrl case "user_typing": let channel = (dictionary["channel"] as? String) ?? "" let user = (dictionary["user"] as? String) ?? "" return .userTyping(channel, user) case "channel_marked": return .channelMarked case "presence_change": let user = (dictionary["user"] as? String) ?? "" let presenceValue: String = (dictionary["presence"] as? String) ?? "" return .presenceChange(user, presenceValue == "active" ? .active : .away) case "file_created": return .fileCreated case "file_public": return .filePublic case "file_shared": return .fileShared case "file_change": return .fileChange case "pref_change": return .prefChange case "group_marked": return .groupMarked case "mpim_marked": return .mpimMarked case "im_marked": return .imMarked case "reaction_added": if let item = dictionary["item"] as? [String: Any] { if (item["type"] as? String) == "message" { let reaction = (dictionary["reaction"] as? String) ?? "" let channel = item["channel"] as? String ?? "" let ts = item["ts"] as? String ?? "" return .messageReactionAdded(reaction, channel, ts) } } return nil case "user_change": return .userChange case "team_rename": let name = (dictionary["name"] as? String) ?? "" return .teamRename(name) case "desktop_notification": let title = ((dictionary["title"] as? String) ?? "") + " " + ((dictionary["subtitle"] as? String) ?? "") let message = ((dictionary["content"] as? String) ?? "") return .desktopNotification(title, message) default: return .unknown("\(type) - \(dictionary)") } case .ping: try self.websocketClient.writeFrame(opcode: .pong) default: return nil } return nil } private func handleMessageEvent(_ dictionary: Dictionary) -> SlackEvent { let channel = (dictionary["channel"] as? String) ?? "" let user = (dictionary["user"] as? String) ?? "unknown" let message = (dictionary["text"] as? String) ?? "" let ts = (dictionary["ts"] as? String) ?? "" let subType = (dictionary["subtype"] as? String) ?? "" switch subType { case "message_changed": if let updatedMessage = (dictionary["message"] as? Dictionary) { let user = (updatedMessage["user"] as? String) ?? "unknown" let ts = (updatedMessage["ts"] as? String) ?? "" let text = (updatedMessage["text"] as? String) ?? "" return .messageChanged(SlackMessage(ts: ts, channel: channel, user: user, text: text, reactions: [])) } case "message_deleted": let ts = (dictionary["deleted_ts"] as? String) ?? "" return .messageDeleted(ts, channel) default:break } return .message(SlackMessage(ts: ts, channel: channel, user: user, text: message, reactions: [])) } } ================================================ FILE: Sources/SlackTeam.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation struct SlackTeam { let selfId: String let name: String let users: [SlackUser] let channels: [SlackChannel] let groups: [SlackGroup] let ims: [SlackIM] let wssUrl: String } ================================================ FILE: Sources/SlackUser.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation struct SlackUser { enum Presence { case active, away } let id: String let name: String let color: String let presence: Presence } ================================================ FILE: Sources/SlackWebClient.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation enum SlackWebClientError: Error { case error(String) } class SlackWebClient { private let token: String init(authenticatedBy token: String) { self.token = token } func rtm() throws -> SlackTeam { return processStartRTMresponse(try self.rpc(forMethod: "rtm.start")) } func history(for channel: String) throws -> [SlackMessage] { var method = "channels.history" if let firstCharacter = channel.first { switch firstCharacter { //TODO - This mapping is rather naive. There should be separated methods for: groups and ims. case "C": method = "channels.history" case "G": method = "groups.history" case "D": method = "im.history" default: break } } let response = try self.rpc(forMethod: method, withParams: ["channel": channel]) guard let messages = response["messages"] as? Array else { throw SlackWebClientError.error("No messages array in the response \(response).") } return messages.map { item in guard let dictionary = item as? Dictionary else { return SlackMessage(ts: "", channel: "", user: "", text: "", reactions: []) } return SlackMessage(ts: (dictionary["ts"] as? String) ?? "", channel: channel, user: (dictionary["user"] as? String) ?? "", text: (dictionary["text"] as? String) ?? "", reactions: (dictionary["reactions"] as? [[String: Any]])?.map({ item in return SlackMessageReaction( name: item["name"] as? String ?? "", count: item["count"] as? Int ?? 0, users: item["users"] as? [String] ?? [] ) }) ?? [] ) } } private func rpc(forMethod rpcMethod: String, withParams params: [String: String] = [:]) throws -> Dictionary { var queryParams = [String: String]() queryParams["token"] = token params.forEach { queryParams[$0.key] = $0.value } let urlString = ("https://slack.com/api/\(rpcMethod)?") + queryParams.map({ $0 + "=" + $1}).joined(separator: "&") guard let url = URL(string: urlString) else { throw SlackWebClientError.error("Could not create URL object.") } let (theData, _) = try URLSession.shared.synchronousDataTask(with: URLRequest(url: url)) guard let data = theData else { throw SlackWebClientError.error("Error receiving data.") } let object = try JSONSerialization.jsonObject(with:data) guard let dict = object as? Dictionary else { throw SlackWebClientError.error("\(rpcMethod)'s response is not a dictionary.") } guard (dict["ok"] as? Bool) == true else { throw SlackWebClientError.error("result not ok \(dict).") } return dict } private func processStartRTMresponse(_ object: Any) -> SlackTeam { return SlackTeam( selfId : object ← "self" ← "id", name : object ← "team" ← "name", users: (object ←← "users").map( { SlackUser(id: $0 ← "id", name: $0 ← "name", color: $0 ← "color", presence: ($0 ← "presence") == "active" ? .active : .away) } ), channels: (object ←← "channels").map({ SlackChannel( id: $0 ← "id", name: $0 ← "name", members: ($0 ←← "members").map({ ($0 as? String) ?? "" }), topic: $0 ← "topic", general: $0 ← "is_general", isMember: $0 ← "is_member" )} ), groups: (object ←← "groups").map( { SlackGroup(id: $0 ← "id", name: $0 ← "name", members: ($0 ←← "members").map({ ($0 as? String) ?? "" }), topic: $0 ← "topic")} ), ims: (object ←← "ims").map({ SlackIM(id: $0 ← "id", user: $0 ← "user") }), wssUrl: object ← "url" ) } } precedencegroup LookupSeparatorPrecedence { associativity: left } infix operator ← : LookupSeparatorPrecedence infix operator ←← : LookupSeparatorPrecedence func ← (left: Any, right: String) -> [String: Any] { if let dict = left as? [String: Any] { return (dict[right] as? [String: Any]) ?? [String: Any]() } return [String: Any]() } func ←← (left: Any, right: String) -> [Any] { if let dict = left as? [String: Any] { return (dict[right] as? [Any]) ?? [Any]() } return [Any]() } func ← (left: Any, right: String) -> String? { if let dict = left as? [String: Any] { return (dict[right] as? String) } return nil } func ← (left: Any, right: String) -> String { if let dict = left as? [String: Any] { return (dict[right] as? String) ?? "" } return "" } func ← (left: Any, right: String) -> Bool? { if let dict = left as? [String: Any] { return (dict[right] as? Bool) } return nil } func ← (left: Any, right: String) -> Bool { if let dict = left as? [String: Any] { return (dict[right] as? Bool) ?? false } return false } func ← (left: [String: Any], right: String) -> [String: Any] { return (left[right] as? [String: Any]) ?? [String: Any]() } func ← (left: [String: Any], right: String) -> Int? { return (left[right] as? Int) ?? nil } func ← (left: [String: Any], right: String) -> Int { return (left[right] as? Int) ?? 0 } func ← (left: [String: Any], right: String) -> String? { return (left[right] as? String) ?? nil } func ← (left: [String: Any], right: String) -> String { return (left[right] as? String) ?? "" } func ← (left: [String: Any], right: String) -> Bool? { return (left[right] as? Bool) } func ← (left: [String: Any], right: String) -> Bool { return (left[right] as? Bool) ?? false } ================================================ FILE: Sources/Socket.swift ================================================ #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) import Darwin #elseif os(Linux) import Glibc #endif struct Socket { static func read(_ socket:Int32, _ buffer: UnsafeMutableRawPointer, _ size:Int) -> Int { #if os(macOS) return Darwin.read(socket, buffer, size) #elseif os(Linux) return Glibc.read(socket, buffer, size) #endif } static func write(_ socket:Int32, _ buffer: Array, _ size:Int) -> Int { #if os(macOS) return Darwin.write(socket, buffer, size) #elseif os(Linux) return Glibc.write(socket, buffer, size) #endif } static func close(_ socket:Int32) -> Int32 { #if os(macOS) return Darwin.close(socket) #elseif os(Linux) return Glibc.close(socket) #endif } } ================================================ FILE: Sources/TLSSocket.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation #if os(OSX) || os(iOS) enum TLSSocketError: Error { case error(String) } class TLSSocket { private var socket: Int32 private let sslContext: SSLContext init(_ address: String, port: Int = 443) throws { guard let context = SSLCreateContext(nil, .clientSide, .streamType) else { throw TLSSocketError.error("SSLCreateContext returned null.") } self.sslContext = context let socket = Darwin.socket(AF_INET, SOCK_STREAM, 0) guard socket != -1 else { throw TLSSocketError.error("Darwin.socket failed: \(errno)") } self.socket = socket var addr = sockaddr_in() addr.sin_len = __uint8_t(MemoryLayout.size) addr.sin_family = sa_family_t(AF_INET) addr.sin_port = UInt16(port).bigEndian guard inet_pton(AF_INET, address, &(addr.sin_addr)) == 1 else { let _ = Darwin.close(self.socket) throw TLSSocketError.error("inet_pton failed.") } if withUnsafePointer(to: &addr, { Darwin.connect(socket, UnsafePointer(OpaquePointer($0)), socklen_t(MemoryLayout.size)) }) == -1 { let _ = Darwin.close(self.socket) throw TLSSocketError.error("Darwin.connect failed: \(errno)") } SSLSetIOFuncs(context, sslRead, sslWrite) guard SSLSetConnection(context, &self.socket) == noErr else { let _ = Darwin.close(self.socket) throw TLSSocketError.error("SSLSetConnection failed.") } let handshakeResult = SSLHandshake(context) guard handshakeResult == noErr else { let _ = Darwin.close(self.socket) throw TLSSocketError.error("SSLHandshake failed: \(handshakeResult)") } } func close() { SSLClose(self.sslContext) let _ = Darwin.close(self.socket) } func writeData(_ data: [UInt8]) throws { var processed = 0 let result = SSLWrite(self.sslContext, data, data.count, &processed) guard result == noErr else { throw TLSSocketError.error("SSLWrite failed: \(result)") } } func readData() throws -> [UInt8] { var processed = 0 var data = [UInt8](repeating: 0, count: 1024) let result = SSLRead(self.sslContext, &data, data.count, &processed) guard result == noErr else { throw TLSSocketError.error("SSLRead failed: \(result)") } data.removeLast(data.count - processed) return data } } func sslRead(_ socketRef: SSLConnectionRef, _ data: UnsafeMutableRawPointer, _ length: UnsafeMutablePointer) -> OSStatus { let socket = socketRef.load(as: Int32.self) var n = 0 while n < length.pointee { let result = read(socket, data + n, length.pointee - n) if result <= 0 { if result == Int(ENOENT) { return errSSLClosedGraceful } if result == Int(ECONNRESET) { return errSSLClosedAbort } return OSStatus(ioErr) } n += result } length.pointee = n return noErr } func sslWrite(_ socketRef: SSLConnectionRef, _ data: UnsafeRawPointer, _ length: UnsafeMutablePointer) -> OSStatus { let socket = socketRef.load(as: Int32.self) var n = 0 while n < length.pointee { let result = write(socket, data + n, length.pointee - n) if result <= 0 { if result == Int(EPIPE) { return errSSLClosedAbort } if result == Int(ECONNRESET) { return errSSLClosedAbort } return OSStatus(ioErr) } n += result } length.pointee = n return noErr } #endif ================================================ FILE: Sources/TerminalCanvas.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation class TerminalCanvas { var buffer = [UInt8]() init() { self.buffer.reserveCapacity(4_000) } @discardableResult func clear() -> TerminalCanvas { self.buffer.removeAll(keepingCapacity: true) return self } @discardableResult func cursor(_ x: Int, _ y: Int) -> TerminalCanvas { self.buffer.append(contentsOf: "\u{001B}[\(y);\(x)H".utf8) return self } @discardableResult func hideCursor() -> TerminalCanvas { self.buffer.append(contentsOf: "\u{001B}[?25l".utf8) return self } @discardableResult func showCursor() -> TerminalCanvas { self.buffer.append(contentsOf: "\u{001B}[?25h".utf8) return self } @discardableResult func clean() -> TerminalCanvas { buffer.append(contentsOf: "\u{001B}[0m\u{001B}[2J".utf8) return self } @discardableResult func color(_ color: Int) -> TerminalCanvas { if color < 0 { buffer.append(contentsOf: "\u{001B}[39m".utf8) } else { buffer.append(contentsOf: "\u{001B}[38;5;\(color)m".utf8) } return self } @discardableResult func background(_ color: Int) -> TerminalCanvas { if color < 0 { buffer.append(contentsOf: "\u{001B}[49m".utf8) } else { buffer.append(contentsOf: "\u{001B}[48;5;\(color)m".utf8) } return self } @discardableResult func blink(_ flag: Bool) -> TerminalCanvas { self.buffer.append(contentsOf: "\u{001B}[\(flag ? "5" : "25")m".utf8) return self } @discardableResult func text(_ text: String) -> TerminalCanvas { buffer.append(contentsOf: text.utf8) return self } @discardableResult func reset() -> TerminalCanvas { buffer.append(contentsOf: "\u{001B}[0m".utf8) return self } } ================================================ FILE: Sources/TerminalDevice.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation enum ControlKey { case null case ctrlC case ctrlD case ctrlF case ctrlH case tab(Bool) case cr case ctrlL case enter case ctrlQ case ctrlS case ctrlU case esc case backspace case arrowUp case arrowDown case arrowLeft case arrowRight case other(Character) } class TerminalDevice { enum TerminalError: Error { case error(String) } private var originalTermios = termios() init() throws { guard tcgetattr(fileno(stdin), &self.originalTermios) == 0 else { throw TerminalError.error("Could not load current terminal config: \(errno)") } try self.terminalEnableRawMode() self.flush(TerminalCanvas().clean().buffer) } var size: (width: Int, height: Int) { var w = winsize() guard ioctl(fileno(stdout), TIOCGWINSZ, &w) == 0 else { exit(1) } return (Int(w.ws_col), Int(w.ws_row)) } func key() -> ControlKey { let c = getwchar() switch c { case 0: return .null case 3: return .ctrlC case 4: return .ctrlD case 6: return .ctrlF case 8: return .ctrlH case 9: return .tab(false) case 10: return .cr case 12: return .ctrlL case 13: return .enter case 17: return .ctrlQ case 19: return .ctrlS case 21: return .ctrlU case 27: let c1 = getwchar() let c2 = getwchar() if c1 == 91 { switch c2 { case 65: return .arrowUp case 66: return .arrowDown case 68: return .arrowLeft case 67: return .arrowRight case 90: return .tab(true) default: break } } return .esc case 127: return .backspace default: return .other(Character(UnicodeScalar(Int(c))!)) } } func flush(_ buffer: [UInt8]) { write(fileno(stdout), buffer, buffer.count) } func reset() throws { guard tcsetattr(fileno(stdin), TCSAFLUSH, &self.originalTermios) == 0 else { throw TerminalError.error("Could not revert the original mode: \(errno)") } self.flush(TerminalCanvas().clean().cursor(1, 1).showCursor().buffer) } private func terminalEnableRawMode() throws { var rawModeTermios = termios() memcpy(&rawModeTermios, &self.originalTermios, MemoryLayout.size) rawModeTermios.c_lflag = UInt(Int32(rawModeTermios.c_lflag) & (~(ECHO | ECHONL | ICANON | IEXTEN | ISIG))) rawModeTermios.c_iflag = UInt(Int32(rawModeTermios.c_iflag) & (~(IGNBRK | BRKINT | INLCR | ICRNL | INPCK | PARMRK | ISTRIP | IXON | IUTF8))) rawModeTermios.c_cflag = UInt(Int32(rawModeTermios.c_cflag) & CS8) rawModeTermios.c_oflag = 0 rawModeTermios.c_cc.17 /*[VTIME]*/ = 0 rawModeTermios.c_cc.16 /*[VMIN] */ = 1 guard tcsetattr(fileno(stdin), TCSAFLUSH, &rawModeTermios) == 0 else { throw TerminalError.error("Could not enable raw mode: \(errno)") } } } ================================================ FILE: Sources/TextLayout.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation struct TextSpan: ExpressibleByStringLiteral { let text: String let textColor: Int let backgroundColor: Int init(stringLiteral value: String) { self.text = value self.textColor = R.color.defaulTextColor self.backgroundColor = R.color.defaultBgColor } init(extendedGraphemeClusterLiteral value: String) { self.text = value self.textColor = R.color.defaulTextColor self.backgroundColor = R.color.defaultBgColor } init(unicodeScalarLiteral value: String) { self.text = value self.textColor = R.color.defaulTextColor self.backgroundColor = R.color.defaultBgColor } init(_ text: String, withColor: Int = R.color.defaulTextColor, withBackground: Int = R.color.defaultBgColor) { self.text = text self.textColor = withColor self.backgroundColor = withBackground } } class TextLayout { let canvas = TerminalCanvas() func layout(_ spans: [TextSpan], alignToWidth width: Int, highlightColor: Int? = nil) -> [[UInt8]] { canvas.clear() var counter = 0 var lines = [[UInt8]]() for span in spans { canvas.background(highlightColor ?? span.backgroundColor) canvas.color(span.textColor) for character in span.text { if character == "\n" { canvas.text(String(repeating: " ", count: width - counter)) counter = 0 lines.append(canvas.buffer) canvas.clear() canvas.background(highlightColor ?? span.backgroundColor) canvas.color(span.textColor) } else { canvas.text(String(character)) counter = counter + 1 if counter == width { counter = 0 lines.append(canvas.buffer) canvas.clear() canvas.background(highlightColor ?? span.backgroundColor) canvas.color(span.textColor) } } } } if counter < width { canvas.text(String(repeating: " ", count: width - counter)) lines.append(canvas.buffer) } return lines } } ================================================ FILE: Sources/URLSession.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation extension URLSession { /// Synchonized version of dataTask(with URLRequest) func synchronousDataTask(with request: URLRequest) throws -> (data: Data?, response: HTTPURLResponse?) { let semaphore = DispatchSemaphore(value: 0) var data: Data? var response: URLResponse? var error: Error? URLSession.shared.dataTask(with: request) { (theData, theResponse, theError) -> Void in // extract information from callback data = theData response = theResponse error = theError // wake semaphore semaphore.signal() }.resume() // wait until signaled _ = semaphore.wait(timeout: .distantFuture) // do we have an error? if let error = error { throw error } return (data: data, response: response as! HTTPURLResponse?) } } ================================================ FILE: Sources/UserInputView.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation class UserInputView { private let renderer = TerminalCanvas() private let terminalDevice: TerminalDevice init(_ device: TerminalDevice) { self.terminalDevice = device } var placeholder = R.string.inputPlaceholder var input = "" var cursor = 0 func draw() { let size = self.terminalDevice.size guard size.width > 0 && size.height > 0 else { return } self.renderer .clear() .hideCursor() .cursor(R.dimen.channelsListWidth + 1, size.height - 1) .background(R.color.defaultBgColor) .color(R.color.channelListBgColor) .text(String(repeating: "─", count: size.width-R.dimen.channelsListWidth)) .cursor(R.dimen.channelsListWidth + 1, size.height) if self.input.isEmpty { self.renderer .color(R.color.userInputPlaceholderTextColor) .background(R.color.userInputBackgorundColor) .text((" " + placeholder).padding(toLength: size.width - R.dimen.channelsListWidth, withPad: " ", startingAt: 0)) .cursor(R.dimen.channelsListWidth + 2, size.height) } else { self.renderer .color(R.color.userInputTextColor) .background(R.color.userInputBackgorundColor) .text((" " + input).padding(toLength: size.width - R.dimen.channelsListWidth, withPad: " ", startingAt: 0)) .cursor(R.dimen.channelsListWidth + 2 + cursor, size.height) } self.renderer.showCursor() self.terminalDevice.flush(renderer.buffer) } } ================================================ FILE: Sources/Utils.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation class Utils { class func shell(_ args: String...) { let task = Process() task.launchPath = "/usr/bin/env" task.arguments = args task.launch() } class func xterm256Color(forUser user: SlackUser) -> Int { // Slack API provides a True-Color value for every user (example: 4b3a5a). Terminal supports only 256 colors. // Instead of using complex alghoritm for finding the closet color from 256 palette, just get modulo 255 value. return (Int(user.color, radix: 16) ?? R.color.messageAuthorTextColor) % 255 } } ================================================ FILE: Sources/WebSocketClient.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation class WebSocketClient { enum Err: Error { case unknownOpCode(String) case unMaskedFrame case notImplemented(String) case invalidFrameLength(String) case io(String) } enum OpCode: UInt8 { case `continue` = 0x00 case close = 0x08 case ping = 0x09 case pong = 0x0A case text = 0x01 case binary = 0x02 } struct Frame { let opcode: OpCode let payload: [UInt8] } private let mask: [UInt8] private let socket: TLSSocket private var inputBuffer = [UInt8]() init(_ host: String, path: String) throws { self.mask = WebSocketClient.provideRandomValues(4) self.socket = try TLSSocket(try WebSocketClient.addressForHost(host)) let secWebSocketKey = Data(WebSocketClient.provideRandomValues(16)).base64EncodedString() let handshakeRequest = [UInt8](( "GET \(path)?encoding=text HTTP/1.1\r\n" + "Host: \(host)\r\n" + "Pragma:no-cache\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "Cache-Control: no-cache\r\n" + "Sec-WebSocket-Version: 13\r\n" + "Sec-WebSocket-Key: \(secWebSocketKey)\r\n\r\n").utf8) try self.socket.writeData(handshakeRequest) //TODO: parse http response in a better way to validate returned Sec-WebSocket-Accept. skipHeaders: while true { let chunk = try self.socket.readData() var iteratpr = chunk.makeIterator() while let b = iteratpr.next() { if b != 13 { inputBuffer.append(b) } if inputBuffer.count >= 2 && inputBuffer.last == 10 && inputBuffer[inputBuffer.endIndex - 2] == 10 { inputBuffer.removeAll(keepingCapacity: true) inputBuffer.append(contentsOf: iteratpr) break skipHeaders } } } } func writeFrame(fin: Bool = true, opcode: OpCode, payload: [UInt8] = []) throws { var data = [UInt8]() data.append(UInt8(fin ? 0x80 : 0x00) | opcode.rawValue) data.append(contentsOf: encodeLengthAndMaskFlag(UInt64(payload.count), mask: self.mask)) data.append(contentsOf: payload.enumerated().map { item in item.element ^ self.mask[item.offset % self.mask.count] }) try self.socket.writeData(data) } private class func provideRandomValues(_ count: Int) -> [UInt8] { var result = [UInt8]() for _ in 0.. [UInt8] { let encodedLngth = UInt8(mask != nil ? 0x80 : 0x00) var encodedBytes = [UInt8]() switch len { case 0...125: encodedBytes.append(encodedLngth | UInt8(len)); case 126...UInt64(UINT16_MAX): encodedBytes.append(encodedLngth | 0x7E); encodedBytes.append(UInt8(len >> 8 & 0xFF)); encodedBytes.append(UInt8(len >> 0 & 0xFF)); default: encodedBytes.append(encodedLngth | 0x7F); encodedBytes.append(UInt8(len >> 56 & 0xFF)); encodedBytes.append(UInt8(len >> 48 & 0xFF)); encodedBytes.append(UInt8(len >> 40 & 0xFF)); encodedBytes.append(UInt8(len >> 32 & 0xFF)); encodedBytes.append(UInt8(len >> 24 & 0xFF)); encodedBytes.append(UInt8(len >> 16 & 0xFF)); encodedBytes.append(UInt8(len >> 08 & 0xFF)); encodedBytes.append(UInt8(len >> 00 & 0xFF)); } if let mask = mask { encodedBytes.append(contentsOf: mask) } return encodedBytes } func waitForFrame() throws -> Frame? { // Handle remaining frames after the handshake. if let frame = try self.lookfForFrame() { return frame } inputBuffer.append(contentsOf: try self.socket.readData()) if let frame = try self.lookfForFrame() { return frame } return nil } private func lookfForFrame() throws -> Frame? { guard inputBuffer.count > 1 else { return nil } let _ /* fin flag */ = inputBuffer[0] & 0x80 != 0 let opc = inputBuffer[0] & 0x0F guard let opcode = OpCode(rawValue: opc) else { // "If an unknown opcode is received, the receiving endpoint MUST _Fail the WebSocket Connection_." // http://tools.ietf.org/html/rfc6455#section-5.2 ( Page 29 ) throw Err.unknownOpCode("\(opc)") } var offset = 2 var len = UInt64(0) switch UInt64(inputBuffer[1] & 0x7F) { case let short where short < 0x7E: len = short case 0x7E: guard inputBuffer.count > 3 else { return nil } len = UInt64(littleEndian: UInt64(inputBuffer[2]) << 8 | UInt64(inputBuffer[3])) offset = 4 case 0x7F: guard inputBuffer.count > 9 else { return nil } let byte2 = UInt64(inputBuffer[2]) << 54 let byte3 = UInt64(inputBuffer[3]) << 48 let byte4 = UInt64(inputBuffer[4]) << 40 let byte5 = UInt64(inputBuffer[5]) << 32 let byte6 = UInt64(inputBuffer[6]) << 24 let byte7 = UInt64(inputBuffer[7]) << 16 let byte8 = UInt64(inputBuffer[8]) << 8 let byte9 = UInt64(inputBuffer[9]) len = UInt64(littleEndian: byte2 | byte3 | byte4 | byte5 | byte6 | byte7 | byte8 | byte9) offset = 10 default: throw Err.invalidFrameLength("Not allowed frame length: \(len)") } let masked = (inputBuffer[1] & 0x80) != 0 guard (len + UInt64(offset) + (masked ? 4 : 0)) <= UInt64(inputBuffer.count) else { return nil } if masked { let mask = [inputBuffer[offset], inputBuffer[offset+1], inputBuffer[offset+2], inputBuffer[offset+3]] offset = offset + mask.count let payload = inputBuffer[offset..<(offset + Int(len /* //TODO fix Int64/Int conversion */))] .enumerated() .map { $0.element ^ mask[Int($0.offset % 4)] } inputBuffer.removeFirst(offset+Int(len)) return Frame(opcode: opcode, payload: payload) } else { let payload = [UInt8](inputBuffer[offset..<(offset + Int(len /* //TODO fix Int64/Int conversion */))]) inputBuffer.removeFirst(offset+Int(len)) return Frame(opcode: opcode, payload: payload) } } private static func addressForHost(_ host: String) throws -> String { guard let info = host.withCString({ gethostbyname($0) }) else { throw Err.io("Could not find address for \(host): gethostbyname failed.") } guard let first = info.pointee.h_addr_list[0] else { throw Err.io("Could not find address for \(host): empty list.") } var buffer = [Int8](repeating: 0, count: 256) guard inet_ntop(AF_INET, first, &buffer, socklen_t(buffer.count)) != nil else { throw Err.io("Could not find address for \(host): inet_ntop failed \(errno).") } return String(cString: buffer) } } ================================================ FILE: Sources/main.swift ================================================ // // slash // // Copyright © 2016 slash Corp. All rights reserved. // import Foundation setlocale(LC_CTYPE,"UTF-8") let device = try TerminalDevice() CrashReporter.watch(usingDevice: device) var token: String! if CommandLine.arguments.count > 1 { token = CommandLine.arguments[1] } else { device.flush(TerminalCanvas() .clean() .cursor(1, 1) .text(String(format: R.string.authHelpMessage, SlackOAuth2.address)).buffer) let slackAuthenticator = SlackOAuth2(clientId: "2296647491.109731100693", clientSecret: "db81eea6c974916693ab746775dbc096", permissions: ["client"]) token = try slackAuthenticator.authenticate() device.flush(TerminalCanvas().clean().buffer) } let application = try Application(usingDevice: device, authenticatedBy: token) signal(SIGWINCH) { _ in application.notifyTerminalSizeHasChanged() } application.run() ================================================ FILE: slash.rb ================================================ class Slash < Formula desc "Slack terminal client written in Swift." homepage "https://github.com/slash-hq/slash" url "https://github.com/slash-hq/slash/archive/0.1.0.tar.gz" sha256 "8a709579ffba7c47b1e1975bb418d72ecbd542539d4cd6f7a72d876808bfbdb2" depends_on :xcode def install xcodebuild "-workspace", "slash.xcodeproj/project.xcworkspace", "-derivedDataPath", "prefix.to_s", "-configuration", "Release", "-scheme", "slash", "SYMROOT=#{prefix}/Build" bin.install(prefix + "Build/Release/slash") end test do system "false" end end ================================================ FILE: slash.sublime-project ================================================ { "build_systems": [ { "shell_cmd": "swift build -v", "name": "Sublime SPM Build for Swift." } ], "folders": [ { "path": ".", "follow_symlinks": true } ] } ================================================ FILE: slash.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 46; objects = { /* Begin PBXBuildFile section */ 2DB32B79220D933300D23E57 /* SlackMessageReaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2DB32B78220D933300D23E57 /* SlackMessageReaction.swift */; }; 7C92EB571E03F3C900F92267 /* TerminalCanvas.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB541E03F3C900F92267 /* TerminalCanvas.swift */; }; 7C92EB581E03F3C900F92267 /* TerminalDevice.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB551E03F3C900F92267 /* TerminalDevice.swift */; }; 7C92EB591E03F3C900F92267 /* TextLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB561E03F3C900F92267 /* TextLayout.swift */; }; 7C92EB651E03F3ED00F92267 /* Application.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB5A1E03F3ED00F92267 /* Application.swift */; }; 7C92EB661E03F3ED00F92267 /* ChannelsListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB5B1E03F3ED00F92267 /* ChannelsListView.swift */; }; 7C92EB671E03F3ED00F92267 /* CrashReporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB5C1E03F3ED00F92267 /* CrashReporter.swift */; }; 7C92EB681E03F3ED00F92267 /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB5D1E03F3ED00F92267 /* main.swift */; }; 7C92EB691E03F3ED00F92267 /* MessagesListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB5E1E03F3ED00F92267 /* MessagesListView.swift */; }; 7C92EB6A1E03F3ED00F92267 /* R.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB5F1E03F3ED00F92267 /* R.swift */; }; 7C92EB6B1E03F3ED00F92267 /* Server.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB601E03F3ED00F92267 /* Server.swift */; }; 7C92EB6C1E03F3ED00F92267 /* SlackAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB611E03F3ED00F92267 /* SlackAdapter.swift */; }; 7C92EB6D1E03F3ED00F92267 /* SlackContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB621E03F3ED00F92267 /* SlackContext.swift */; }; 7C92EB6E1E03F3ED00F92267 /* UserInputView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB631E03F3ED00F92267 /* UserInputView.swift */; }; 7C92EB6F1E03F3ED00F92267 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB641E03F3ED00F92267 /* Utils.swift */; }; 7C92EB7D1E03F3FC00F92267 /* SlackChannel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB701E03F3FC00F92267 /* SlackChannel.swift */; }; 7C92EB7E1E03F3FC00F92267 /* SlackEmojiDecoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB711E03F3FC00F92267 /* SlackEmojiDecoder.swift */; }; 7C92EB7F1E03F3FC00F92267 /* SlackEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB721E03F3FC00F92267 /* SlackEvent.swift */; }; 7C92EB801E03F3FC00F92267 /* SlackGroup.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB731E03F3FC00F92267 /* SlackGroup.swift */; }; 7C92EB811E03F3FC00F92267 /* SlackIM.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB741E03F3FC00F92267 /* SlackIM.swift */; }; 7C92EB821E03F3FC00F92267 /* SlackMessage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB751E03F3FC00F92267 /* SlackMessage.swift */; }; 7C92EB831E03F3FC00F92267 /* SlackOAuth2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB761E03F3FC00F92267 /* SlackOAuth2.swift */; }; 7C92EB841E03F3FC00F92267 /* SlackRealTimeClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB771E03F3FC00F92267 /* SlackRealTimeClient.swift */; }; 7C92EB851E03F3FC00F92267 /* SlackTeam.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB781E03F3FC00F92267 /* SlackTeam.swift */; }; 7C92EB861E03F3FC00F92267 /* SlackUser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB791E03F3FC00F92267 /* SlackUser.swift */; }; 7C92EB871E03F3FC00F92267 /* SlackWebClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB7A1E03F3FC00F92267 /* SlackWebClient.swift */; }; 7C92EB881E03F3FC00F92267 /* TLSSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB7B1E03F3FC00F92267 /* TLSSocket.swift */; }; 7C92EB891E03F3FC00F92267 /* WebSocketClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C92EB7C1E03F3FC00F92267 /* WebSocketClient.swift */; }; 7C9FE5F11E18F9B900FB8166 /* Socket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C9FE5F01E18F9B900FB8166 /* Socket.swift */; }; D42C5DF71E156BEE008CDA3C /* URLSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = D42C5DF61E156BEE008CDA3C /* URLSession.swift */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ 7CBB81F01DC12E8B00DC0334 /* CopyFiles */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = /usr/share/man/man1/; dstSubfolderSpec = 0; files = ( ); runOnlyForDeploymentPostprocessing = 1; }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ 2DB32B78220D933300D23E57 /* SlackMessageReaction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackMessageReaction.swift; path = Sources/SlackMessageReaction.swift; sourceTree = SOURCE_ROOT; }; 7C92EB541E03F3C900F92267 /* TerminalCanvas.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = TerminalCanvas.swift; path = Sources/TerminalCanvas.swift; sourceTree = SOURCE_ROOT; }; 7C92EB551E03F3C900F92267 /* TerminalDevice.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = TerminalDevice.swift; path = Sources/TerminalDevice.swift; sourceTree = SOURCE_ROOT; }; 7C92EB561E03F3C900F92267 /* TextLayout.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = TextLayout.swift; path = Sources/TextLayout.swift; sourceTree = SOURCE_ROOT; }; 7C92EB5A1E03F3ED00F92267 /* Application.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Application.swift; path = Sources/Application.swift; sourceTree = SOURCE_ROOT; }; 7C92EB5B1E03F3ED00F92267 /* ChannelsListView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = ChannelsListView.swift; path = Sources/ChannelsListView.swift; sourceTree = SOURCE_ROOT; }; 7C92EB5C1E03F3ED00F92267 /* CrashReporter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = CrashReporter.swift; path = Sources/CrashReporter.swift; sourceTree = SOURCE_ROOT; }; 7C92EB5D1E03F3ED00F92267 /* main.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = main.swift; path = Sources/main.swift; sourceTree = SOURCE_ROOT; }; 7C92EB5E1E03F3ED00F92267 /* MessagesListView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = MessagesListView.swift; path = Sources/MessagesListView.swift; sourceTree = SOURCE_ROOT; }; 7C92EB5F1E03F3ED00F92267 /* R.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = R.swift; path = Sources/R.swift; sourceTree = SOURCE_ROOT; }; 7C92EB601E03F3ED00F92267 /* Server.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Server.swift; path = Sources/Server.swift; sourceTree = SOURCE_ROOT; }; 7C92EB611E03F3ED00F92267 /* SlackAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackAdapter.swift; path = Sources/SlackAdapter.swift; sourceTree = SOURCE_ROOT; }; 7C92EB621E03F3ED00F92267 /* SlackContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackContext.swift; path = Sources/SlackContext.swift; sourceTree = SOURCE_ROOT; }; 7C92EB631E03F3ED00F92267 /* UserInputView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = UserInputView.swift; path = Sources/UserInputView.swift; sourceTree = SOURCE_ROOT; }; 7C92EB641E03F3ED00F92267 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Utils.swift; path = Sources/Utils.swift; sourceTree = SOURCE_ROOT; }; 7C92EB701E03F3FC00F92267 /* SlackChannel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackChannel.swift; path = Sources/SlackChannel.swift; sourceTree = SOURCE_ROOT; }; 7C92EB711E03F3FC00F92267 /* SlackEmojiDecoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackEmojiDecoder.swift; path = Sources/SlackEmojiDecoder.swift; sourceTree = SOURCE_ROOT; }; 7C92EB721E03F3FC00F92267 /* SlackEvent.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackEvent.swift; path = Sources/SlackEvent.swift; sourceTree = SOURCE_ROOT; }; 7C92EB731E03F3FC00F92267 /* SlackGroup.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackGroup.swift; path = Sources/SlackGroup.swift; sourceTree = SOURCE_ROOT; }; 7C92EB741E03F3FC00F92267 /* SlackIM.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackIM.swift; path = Sources/SlackIM.swift; sourceTree = SOURCE_ROOT; }; 7C92EB751E03F3FC00F92267 /* SlackMessage.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackMessage.swift; path = Sources/SlackMessage.swift; sourceTree = SOURCE_ROOT; }; 7C92EB761E03F3FC00F92267 /* SlackOAuth2.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackOAuth2.swift; path = Sources/SlackOAuth2.swift; sourceTree = SOURCE_ROOT; }; 7C92EB771E03F3FC00F92267 /* SlackRealTimeClient.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackRealTimeClient.swift; path = Sources/SlackRealTimeClient.swift; sourceTree = SOURCE_ROOT; }; 7C92EB781E03F3FC00F92267 /* SlackTeam.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackTeam.swift; path = Sources/SlackTeam.swift; sourceTree = SOURCE_ROOT; }; 7C92EB791E03F3FC00F92267 /* SlackUser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackUser.swift; path = Sources/SlackUser.swift; sourceTree = SOURCE_ROOT; }; 7C92EB7A1E03F3FC00F92267 /* SlackWebClient.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SlackWebClient.swift; path = Sources/SlackWebClient.swift; sourceTree = SOURCE_ROOT; }; 7C92EB7B1E03F3FC00F92267 /* TLSSocket.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = TLSSocket.swift; path = Sources/TLSSocket.swift; sourceTree = SOURCE_ROOT; }; 7C92EB7C1E03F3FC00F92267 /* WebSocketClient.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = WebSocketClient.swift; path = Sources/WebSocketClient.swift; sourceTree = SOURCE_ROOT; }; 7C9FE5F01E18F9B900FB8166 /* Socket.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Socket.swift; path = Sources/Socket.swift; sourceTree = SOURCE_ROOT; }; 7CBB81F21DC12E8B00DC0334 /* slash */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = slash; sourceTree = BUILT_PRODUCTS_DIR; }; D42C5DF61E156BEE008CDA3C /* URLSession.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = URLSession.swift; path = Sources/URLSession.swift; sourceTree = SOURCE_ROOT; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 7CBB81EF1DC12E8B00DC0334 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 7C4A722A1DE5CC91005A72EF /* Sources */ = { isa = PBXGroup; children = ( D42C5DF51E156A2A008CDA3C /* Extensions */, 7C4A725F1DE5CCD4005A72EF /* App */, 7C4A725E1DE5CCB6005A72EF /* Slack */, 7C4A725D1DE5CCA3005A72EF /* Terminal */, ); name = Sources; path = ../Sources; sourceTree = ""; }; 7C4A725D1DE5CCA3005A72EF /* Terminal */ = { isa = PBXGroup; children = ( 7C92EB541E03F3C900F92267 /* TerminalCanvas.swift */, 7C92EB551E03F3C900F92267 /* TerminalDevice.swift */, 7C92EB561E03F3C900F92267 /* TextLayout.swift */, ); name = Terminal; sourceTree = ""; }; 7C4A725E1DE5CCB6005A72EF /* Slack */ = { isa = PBXGroup; children = ( 7C9FE5F01E18F9B900FB8166 /* Socket.swift */, 7C92EB701E03F3FC00F92267 /* SlackChannel.swift */, 7C92EB711E03F3FC00F92267 /* SlackEmojiDecoder.swift */, 7C92EB721E03F3FC00F92267 /* SlackEvent.swift */, 7C92EB731E03F3FC00F92267 /* SlackGroup.swift */, 7C92EB741E03F3FC00F92267 /* SlackIM.swift */, 7C92EB751E03F3FC00F92267 /* SlackMessage.swift */, 2DB32B78220D933300D23E57 /* SlackMessageReaction.swift */, 7C92EB761E03F3FC00F92267 /* SlackOAuth2.swift */, 7C92EB771E03F3FC00F92267 /* SlackRealTimeClient.swift */, 7C92EB781E03F3FC00F92267 /* SlackTeam.swift */, 7C92EB791E03F3FC00F92267 /* SlackUser.swift */, 7C92EB7A1E03F3FC00F92267 /* SlackWebClient.swift */, 7C92EB7B1E03F3FC00F92267 /* TLSSocket.swift */, 7C92EB7C1E03F3FC00F92267 /* WebSocketClient.swift */, ); name = Slack; sourceTree = ""; }; 7C4A725F1DE5CCD4005A72EF /* App */ = { isa = PBXGroup; children = ( 7C92EB5A1E03F3ED00F92267 /* Application.swift */, 7C92EB5B1E03F3ED00F92267 /* ChannelsListView.swift */, 7C92EB5C1E03F3ED00F92267 /* CrashReporter.swift */, 7C92EB5D1E03F3ED00F92267 /* main.swift */, 7C92EB5E1E03F3ED00F92267 /* MessagesListView.swift */, 7C92EB5F1E03F3ED00F92267 /* R.swift */, 7C92EB601E03F3ED00F92267 /* Server.swift */, 7C92EB611E03F3ED00F92267 /* SlackAdapter.swift */, 7C92EB621E03F3ED00F92267 /* SlackContext.swift */, 7C92EB631E03F3ED00F92267 /* UserInputView.swift */, 7C92EB641E03F3ED00F92267 /* Utils.swift */, ); name = App; sourceTree = ""; }; 7CBB81E91DC12E8B00DC0334 = { isa = PBXGroup; children = ( 7C4A722A1DE5CC91005A72EF /* Sources */, 7CBB81F31DC12E8B00DC0334 /* Products */, ); sourceTree = ""; }; 7CBB81F31DC12E8B00DC0334 /* Products */ = { isa = PBXGroup; children = ( 7CBB81F21DC12E8B00DC0334 /* slash */, ); name = Products; sourceTree = ""; }; D42C5DF51E156A2A008CDA3C /* Extensions */ = { isa = PBXGroup; children = ( D42C5DF61E156BEE008CDA3C /* URLSession.swift */, ); name = Extensions; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 7CBB81F11DC12E8B00DC0334 /* slash */ = { isa = PBXNativeTarget; buildConfigurationList = 7CBB81F91DC12E8B00DC0334 /* Build configuration list for PBXNativeTarget "slash" */; buildPhases = ( 7CBB81EE1DC12E8B00DC0334 /* Sources */, 7CBB81EF1DC12E8B00DC0334 /* Frameworks */, 7CBB81F01DC12E8B00DC0334 /* CopyFiles */, ); buildRules = ( ); dependencies = ( ); name = slash; productName = swiftslack; productReference = 7CBB81F21DC12E8B00DC0334 /* slash */; productType = "com.apple.product-type.tool"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 7CBB81EA1DC12E8B00DC0334 /* Project object */ = { isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0800; LastUpgradeCheck = 1000; ORGANIZATIONNAME = kolakowski; TargetAttributes = { 7CBB81F11DC12E8B00DC0334 = { CreatedOnToolsVersion = 8.0; LastSwiftMigration = 0900; ProvisioningStyle = Automatic; }; }; }; buildConfigurationList = 7CBB81ED1DC12E8B00DC0334 /* Build configuration list for PBXProject "slash" */; compatibilityVersion = "Xcode 3.2"; developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( en, ); mainGroup = 7CBB81E91DC12E8B00DC0334; productRefGroup = 7CBB81F31DC12E8B00DC0334 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 7CBB81F11DC12E8B00DC0334 /* slash */, ); }; /* End PBXProject section */ /* Begin PBXSourcesBuildPhase section */ 7CBB81EE1DC12E8B00DC0334 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 7C92EB801E03F3FC00F92267 /* SlackGroup.swift in Sources */, 7C92EB6B1E03F3ED00F92267 /* Server.swift in Sources */, 7C92EB6E1E03F3ED00F92267 /* UserInputView.swift in Sources */, 2DB32B79220D933300D23E57 /* SlackMessageReaction.swift in Sources */, 7C92EB691E03F3ED00F92267 /* MessagesListView.swift in Sources */, 7C92EB881E03F3FC00F92267 /* TLSSocket.swift in Sources */, 7C92EB6F1E03F3ED00F92267 /* Utils.swift in Sources */, 7C92EB871E03F3FC00F92267 /* SlackWebClient.swift in Sources */, 7C92EB811E03F3FC00F92267 /* SlackIM.swift in Sources */, 7C92EB7D1E03F3FC00F92267 /* SlackChannel.swift in Sources */, 7C92EB861E03F3FC00F92267 /* SlackUser.swift in Sources */, 7C92EB671E03F3ED00F92267 /* CrashReporter.swift in Sources */, 7C92EB821E03F3FC00F92267 /* SlackMessage.swift in Sources */, 7C92EB681E03F3ED00F92267 /* main.swift in Sources */, 7C92EB7F1E03F3FC00F92267 /* SlackEvent.swift in Sources */, 7C92EB891E03F3FC00F92267 /* WebSocketClient.swift in Sources */, 7C92EB6C1E03F3ED00F92267 /* SlackAdapter.swift in Sources */, 7C92EB6A1E03F3ED00F92267 /* R.swift in Sources */, 7C92EB661E03F3ED00F92267 /* ChannelsListView.swift in Sources */, 7C92EB7E1E03F3FC00F92267 /* SlackEmojiDecoder.swift in Sources */, 7C92EB651E03F3ED00F92267 /* Application.swift in Sources */, 7C92EB831E03F3FC00F92267 /* SlackOAuth2.swift in Sources */, 7C92EB6D1E03F3ED00F92267 /* SlackContext.swift in Sources */, D42C5DF71E156BEE008CDA3C /* URLSession.swift in Sources */, 7C92EB841E03F3FC00F92267 /* SlackRealTimeClient.swift in Sources */, 7C92EB851E03F3FC00F92267 /* SlackTeam.swift in Sources */, 7C9FE5F11E18F9B900FB8166 /* Socket.swift in Sources */, 7C92EB581E03F3C900F92267 /* TerminalDevice.swift in Sources */, 7C92EB571E03F3C900F92267 /* TerminalCanvas.swift in Sources */, 7C92EB591E03F3C900F92267 /* TextLayout.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin XCBuildConfiguration section */ 7CBB81F71DC12E8B00DC0334 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_SUSPICIOUS_MOVES = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGN_IDENTITY = "-"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MACOSX_DEPLOYMENT_TARGET = 10.12; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; SWIFT_INCLUDE_PATHS = ""; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 4.2; }; name = Debug; }; 7CBB81F81DC12E8B00DC0334 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_SUSPICIOUS_MOVES = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGN_IDENTITY = "-"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MACOSX_DEPLOYMENT_TARGET = 10.12; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_INCLUDE_PATHS = ""; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 4.2; }; name = Release; }; 7CBB81FA1DC12E8B00DC0334 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { LD_RUNPATH_SEARCH_PATHS = "@executable_path"; MACOSX_DEPLOYMENT_TARGET = 10.11; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_SWIFT3_OBJC_INFERENCE = Default; SWIFT_VERSION = 4.0; }; name = Debug; }; 7CBB81FB1DC12E8B00DC0334 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { LD_RUNPATH_SEARCH_PATHS = "@executable_path"; MACOSX_DEPLOYMENT_TARGET = 10.11; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_SWIFT3_OBJC_INFERENCE = Default; SWIFT_VERSION = 4.0; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 7CBB81ED1DC12E8B00DC0334 /* Build configuration list for PBXProject "slash" */ = { isa = XCConfigurationList; buildConfigurations = ( 7CBB81F71DC12E8B00DC0334 /* Debug */, 7CBB81F81DC12E8B00DC0334 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 7CBB81F91DC12E8B00DC0334 /* Build configuration list for PBXNativeTarget "slash" */ = { isa = XCConfigurationList; buildConfigurations = ( 7CBB81FA1DC12E8B00DC0334 /* Debug */, 7CBB81FB1DC12E8B00DC0334 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 7CBB81EA1DC12E8B00DC0334 /* Project object */; } ================================================ FILE: slash.xcodeproj/project.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: slash.xcodeproj/xcshareddata/xcschemes/slash.xcscheme ================================================