Compare commits

...

63 Commits

Author SHA1 Message Date
Peter Zignego 58bade8ec9 Bump version 2017-01-04 22:10:18 -05:00
Peter Zignego 7d7f5c40d6 Update readme 2017-01-04 22:09:18 -05:00
Peter Zignego c9fd54d106 Merge pull request #66 from pvzig/3.1.7
3.1.7
2017-01-04 22:08:10 -05:00
Peter Zignego 2f1ce799ad URLComponents and WebAPI clean up 2017-01-04 22:06:47 -05:00
Peter Zignego 7f02f4cf99 Update readme 2017-01-03 22:07:57 -05:00
Peter Zignego a9066c0d0a Bump version 2017-01-03 21:29:49 -05:00
Peter Zignego 29739dba74 Merge pull request #65 from pvzig/minor-updates
Code styling
2017-01-03 21:20:00 -05:00
Peter Zignego d60a7094a4 Readme 2017-01-03 21:18:58 -05:00
Peter Zignego 7edd4210f6 Code quality improvements 2017-01-02 22:41:03 -05:00
Peter Zignego 2abaecbd14 Lowercase enums 2017-01-02 22:39:56 -05:00
Peter Zignego 346499e03b Update podspec version 2016-11-25 12:46:48 -05:00
Peter Zignego bc72a52bf5 Update readme 2016-11-24 12:37:48 -05:00
Peter Zignego 0ebd3cb0e7 Merge pull request #60 from pvzig/ios-fix
Fix iOS crash + Swift 3 style changes
2016-11-24 12:19:39 -05:00
Peter Zignego 5d7064ee13 Podfile + versioning 2016-11-24 12:16:53 -05:00
Peter Zignego d02768ddad Bump starscream version 2016-11-24 12:01:54 -05:00
Peter Zignego dbc7b361c8 Merge branch 'master' into ios-fix 2016-11-24 11:59:50 -05:00
Peter Zignego a0de46e3c7 Code quality improvements 2016-11-20 22:10:44 -05:00
Peter Zignego 2d6e19baee Bump starscream version 2016-11-20 22:07:06 -05:00
Peter Zignego 21ec3cb2a1 Fix iOS crash 2016-11-20 22:04:50 -05:00
Peter Zignego cb542da068 Merge pull request #59 from MarcusSmith/master
Fix File Upload Bug
2016-11-18 14:16:18 -05:00
Marcus Smith 788b4e4f7a Remove File data from upload's query parameters, which was preventing a proper URL from being created from the request string 2016-11-18 14:14:02 -05:00
Peter Zignego 24b2292cba Request string bugfix 2016-11-17 16:48:00 -05:00
Peter Zignego 72866262d2 Fix request string bug 2016-11-17 16:30:28 -05:00
Peter Zignego acabbb6c03 Update README.md 2016-11-17 15:04:18 -05:00
Peter Zignego fff0f0befc Merge branch 'master' of https://github.com/pvzig/SlackKit into ios-fix
# Conflicts:
#	SlackKit/Sources/WebAPI.swift
2016-11-17 14:44:35 -05:00
Peter Zignego cf0675dac2 Merge pull request #58 from stucarney/master
Added missing support for chat.meMessage endpoint
2016-11-17 09:08:54 -05:00
Stu Carney 1cffa0ba74 Added missing support for chat.meMessage endpoint 2016-11-16 20:00:22 -06:00
Peter Zignego 9ebd8182a6 Lowercase enums 2016-11-13 17:26:32 -05:00
Peter Zignego 63a8ae7f08 Lowercase enums 2016-11-13 15:34:27 -05:00
Peter Zignego 992f94e870 Lowercase error enums 2016-11-13 15:32:50 -05:00
Peter Zignego 1c476c77ad Lowercase enums 2016-11-11 14:59:43 -05:00
Peter Zignego 28bd612ca0 Carthage search paths 2016-10-11 21:18:34 -04:00
Peter Zignego 45cf2a7ac0 Add back links for carthage 2016-10-11 21:12:31 -04:00
Peter Zignego f7c986c65c Update dependency managers 2016-10-11 21:01:17 -04:00
Peter Zignego ca43df4475 Update project file 2016-10-11 19:43:14 -04:00
Peter Zignego ef71b6abf0 Swifter compatability 2016-10-11 19:41:36 -04:00
Peter Zignego 3ff922a2c0 Project file update 2016-10-11 19:41:28 -04:00
Peter Zignego 646c371bd3 SPM compatability 2016-10-01 12:37:13 -04:00
Peter Zignego 36401009f8 Version bump 2016-09-26 00:05:13 -04:00
Peter Zignego b837554dcf Delete Package.swift until SPM compatability is restored 2016-09-25 23:54:25 -04:00
Peter Zignego 0ba0e019ae Update README.md 2016-09-25 23:52:53 -04:00
Peter Zignego 8771ef3f0a Update readme 2016-09-25 23:51:32 -04:00
Peter Zignego 71e7238483 Merge branch 'swift3'
# Conflicts:
#	README.md
#	SlackKit/Sources/Action.swift
#	SlackKit/Sources/Response.swift
#	SlackKit/Sources/SlackKit.swift
2016-09-25 20:35:45 -04:00
Peter Zignego b75c10fca6 Merge pull request #53 from pvzig/swift3-GM
Swift 3
2016-09-25 20:31:44 -04:00
Peter Zignego 50f85ac103 Carthage 2016-09-20 00:23:26 -04:00
Peter Zignego a7cbb84b34 Update starscream delegate 2016-09-20 00:23:08 -04:00
Peter Zignego ed6789c9a5 Swift 3 update 2016-09-19 23:59:10 -04:00
Peter Zignego ca444930a4 GM 2016-09-14 21:39:32 -04:00
Peter Zignego 21051864ec Add badges 2016-09-13 00:10:55 -04:00
Peter Zignego 36d1553072 Update README.md 2016-09-12 23:42:17 -04:00
Peter Zignego eb14758846 Add badges 2016-09-12 23:40:48 -04:00
Peter Zignego bf3a5c2422 Merge pull request #47 from hiragram/add-missing-scope
Add MissingScope
2016-08-21 22:40:59 -04:00
Yuya 98fd1342e7 Add MissingScope 2016-08-21 13:38:49 +09:00
Peter Zignego 183ed91cb8 Merge branch 'xcode8b4' into swift3 2016-08-03 22:47:16 -04:00
Peter Zignego c241dcf1df Xcode 8 beta 4 2016-08-03 22:47:03 -04:00
Peter Zignego 8007fa6f0f Include style in Action JSON dictionary 2016-08-02 23:24:12 -04:00
Peter Zignego 7ab973a03b Include style in Action JSON dictionary 2016-08-02 23:21:16 -04:00
Peter Zignego 987be40c91 Fix callback bug when authing via a token 2016-07-26 19:07:53 -04:00
Peter Zignego 2e71ac6876 Bug fix 2016-07-23 11:12:14 -04:00
Peter Zignego c428cac537 Update readme 2016-07-20 21:44:30 -04:00
Peter Zignego 18c6516df9 Remove Cocoapods 2016-07-20 21:32:57 -04:00
Peter Zignego fe450a7db2 Set swift version 2016-07-20 21:32:41 -04:00
Peter Zignego bb57f59553 Swift 3 support 2016-07-20 18:31:03 -04:00
60 changed files with 1434 additions and 1539 deletions
+1
View File
@@ -16,6 +16,7 @@ DerivedData
*.hmap
*.ipa
*.xcuserstate
*.DS_Store
# SwiftPM
Packages/
+1 -1
View File
@@ -1 +1 @@
2.2
3.0
+2 -2
View File
@@ -1,2 +1,2 @@
github "daltoniam/Starscream" ~> 1.0
github "glock45/swifter" "d7c820bfc9260e469094b5f8d3d101b30c4a8fac"
github "https://github.com/daltoniam/Starscream" == 2.0.2
github "https://github.com/pvzig/swifter.git" == 3.0.4
+2 -2
View File
@@ -1,2 +1,2 @@
github "daltoniam/Starscream" "1.1.3"
github "glock45/swifter" "d7c820bfc9260e469094b5f8d3d101b30c4a8fac"
github "daltoniam/Starscream" "2.0.2"
github "pvzig/swifter" "3.0.4"
+4 -28
View File
@@ -1,35 +1,11 @@
//
// Package.swift
//
// Copyright © 2016 Peter Zignego. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import PackageDescription
let package = Package(
name: "SlackKit",
targets: [],
dependencies: [
.Package(url: "https://github.com/daltoniam/Starscream",
majorVersion: 1),
.Package(url: "https://github.com/httpswift/swifter", majorVersion: 1)
],
exclude: ["Examples", "Carthage", "Pods"]
.Package(url: "https://github.com/pvzig/swifter.git",
majorVersion: 3, minor: 0),
.Package(url: "https://github.com/daltoniam/Starscream", majorVersion: 2, minor: 0)
]
)
+6 -6
View File
@@ -3,16 +3,16 @@ source 'https://github.com/CocoaPods/Specs.git'
use_frameworks!
target 'SlackKit OS X' do
pod 'Starscream'
pod 'Swifter'
pod 'Starscream', '~> 2.0.2'
pod 'Swifter', :git => 'https://github.com/pvzig/swifter.git', :tag => '3.0.4'
end
target 'SlackKit iOS' do
pod 'Starscream'
pod 'Swifter'
pod 'Starscream', '~> 2.0.2'
pod 'Swifter', :git => 'https://github.com/pvzig/swifter.git', :tag => '3.0.4'
end
target 'SlackKit tvOS' do
pod 'Starscream'
pod 'Swifter'
pod 'Starscream', '~> 2.0.2'
pod 'Swifter', :git => 'https://github.com/pvzig/swifter.git', :tag => '3.0.4'
end
+18 -8
View File
@@ -1,15 +1,25 @@
PODS:
- Starscream (1.1.3)
- Swifter (1.2.6)
- Starscream (2.0.2)
- Swifter (1.3.2)
DEPENDENCIES:
- Starscream
- Swifter
- Starscream (~> 2.0.2)
- Swifter (from `https://github.com/pvzig/swifter.git`, tag `3.0.4`)
EXTERNAL SOURCES:
Swifter:
:git: https://github.com/pvzig/swifter.git
:tag: 3.0.4
CHECKOUT OPTIONS:
Swifter:
:git: https://github.com/pvzig/swifter.git
:tag: 3.0.4
SPEC CHECKSUMS:
Starscream: d662732354b40dd19ed1ece3e3c44c80b536b83c
Swifter: c6f13d053398f1e2f209c7a394dfd5e863ae0157
Starscream: 6c135a34e0a6e60cedaa0b30db67a4c05cf7cd38
Swifter: dd1800ba8eb3e28b22b8bd20f91a8561a0110fac
PODFILE CHECKSUM: 372d57254c34897042ce228cf421d7c9cc5caf9f
PODFILE CHECKSUM: cd86ea0f8422027c9d5fa3c40243ae7a816fb79a
COCOAPODS: 1.0.1
COCOAPODS: 1.1.0.rc.3
+76 -70
View File
@@ -1,21 +1,28 @@
![SlackKit](https://cloud.githubusercontent.com/assets/8311605/10260893/5ec60f96-694e-11e5-91fd-da6845942201.png)
![Swift Version](https://img.shields.io/badge/Swift-3.0-orange.svg) ![Plaforms](https://img.shields.io/badge/Platforms-macOS,iOS,tvOS-lightgrey.svg) ![License MIT](https://img.shields.io/badge/License-MIT-lightgrey.svg) [![CocoaPods compatible](https://img.shields.io/badge/CocoaPods-compatible-brightgreen.svg)](https://cocoapods.org) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-brightgreen.svg)](https://github.com/Carthage/Carthage) [![SwiftPM compatible](https://img.shields.io/badge/SwiftPM-compatible-brightgreen.svg)](https://github.com/apple/swift-package-manager)
## SlackKit: A Swift Slack Client Library
### Description
This is a Slack client library for OS X, iOS, and tvOS written in Swift. It's intended to expose all of the functionality of Slack's [Real Time Messaging API](https://api.slack.com/rtm) as well as the [web APIs](https://api.slack.com/web) that are accessible to [bot users](https://api.slack.com/bot-users). SlackKit also supports Slacks [OAuth 2.0](https://api.slack.com/docs/oauth) flow including the [Add to Slack](https://api.slack.com/docs/slack-button) and [Sign in with Slack](https://api.slack.com/docs/sign-in-with-slack) buttons, [incoming webhooks](https://api.slack.com/incoming-webhooks), [slash commands](https://api.slack.com/slash-commands), and [message buttons](https://api.slack.com/docs/message-buttons).
SlackKit also has alpha support for: [Swift 3](https://github.com/pvzig/SlackKit/tree/swift3), [Linux](https://github.com/pvzig/SlackKit/tree/linux)
This is the **Swift 3** branch of SlackKit. SlackKit also has support for [Swift 2.3](https://github.com/pvzig/SlackKit/tree/swift2.3) and [Linux](https://github.com/pvzig/SlackKit/tree/linux).
#### Building the SlackKit Framework
To build the SlackKit project directly, first build the dependencies using Carthage or CocoaPods. To use the framework in your application, install it in one of the following ways:
### Installation
#### CocoaPods
Add the pod to your podfile:
Add SlackKit to your pod file:
```
pod 'SlackKit'
use_frameworks!
pod 'SlackKit', '~> 3.1.7'
```
and run
```
# Use CocoaPods version >= 1.1.0
pod install
```
@@ -23,29 +30,28 @@ pod install
Add SlackKit to your Cartfile:
```
github "pvzig/SlackKit" ~> 2.0
github "https://github.com/pvzig/slackkit.git"
```
and run
```
carthage bootstrap
```
**Note:** SlackKit currently takes a _long_ time for the compiler to compile with optimizations turned on. I'm currently exploring a potential fix for this issue. In the meantime, you may want to skip the waiting and build it in the debug configuration instead:
```
carthage bootstrap --configuration "Debug"
```
Drag the built `SlackKit.framework` into your Xcode project.
#### Swift Package Manager
Add SlackKit to your Package.swift
```swift
import PackageDescription
let package = Package(
dependencies: [
.Package(url: "https://github.com/pvzig/SlackKit.git", majorVersion: 2)
]
dependencies: [
.Package(url: "https://github.com/pvzig/SlackKit.git", majorVersion: 3)
]
)
```
Run `swift build` on your applications main directory.
To use the library in your project import it:
@@ -78,7 +84,7 @@ incoming.postMessage(message)
#### Slash Commands
After [configuring your slash command in Slack](https://my.slack.com/services/new/slash-commands) (you can also provide slash commands as part of a [Slack App](https://api.slack.com/slack-apps)), initialize a webhook server with the token for the slash command, a configured route, and a response.
```swift
let response = Response(text: "Hello, World!", responseType: .InChannel)
let response = Response(text: "Hello, World!", responseType: .inChannel)
let webhook = WebhookServer(token: "SLASH-COMMAND-TOKEN", route: "hello_world", response: response)
webhook.start()
```
@@ -101,7 +107,7 @@ let attachment = Attachment(fallback: "Hello World Attachment", title: "Attachme
To act on message actions, initialize an instance of the `MessageActionServer` using your apps verification token, your specified interactive messages request URL route, and a `MessageActionResponder`:
```swift
let action = Action(name: "hello_world", text: "Hello, World!")
let response = Response(text: "Hello, 🌎!", responseType: .InChannel)
let response = Response(text: "Hello, 🌎!", responseType: .inChannel)
let responder = MessageActionResponder(responses: [(action, response)])
let server = MessageActionServer(token: "SLACK-APP-VERIFICATION-TOKEN", route: "actions", responder: responder)
server.start()
@@ -142,6 +148,7 @@ SlackKit currently supports the a subset of the Slack Web APIs that are availabl
- channels.setPurpose
- channels.setTopic
- chat.delete
- chat.meMessage
- chat.postMessage
- chat.update
- emoji.list
@@ -189,23 +196,22 @@ SlackKit currently supports the a subset of the Slack Web APIs that are availabl
They can be accessed through a Client objects `webAPI` property:
```swift
client.webAPI.authenticationTest({ (authenticated) -> Void in
print(authenticated)
}){(error) -> Void in
client.webAPI.authenticationTest({(auth) in
print(auth)
}, failure: {(error) in
print(error)
}
})
```
#### Delegate methods
To receive delegate callbacks for events, register an object as the delegate for those events using the `onClientInitalization` block:
```swift
let bot = SlackKit(clientID: "CLIENT_ID", clientSecret: "CLIENT_SECRET")
let bot = SlackKit(clientID: clientID, clientSecret: clientSecret)
bot.onClientInitalization = { (client: Client) in
dispatch_async(dispatch_get_main_queue(), {
client.connectionEventsDelegate = self
DispatchQueue.main.async(execute: {
client.messageEventsDelegate = self
})
})
}
```
@@ -215,90 +221,90 @@ There are a number of delegates that you can set to receive callbacks for certai
##### ConnectionEventsDelegate
```swift
clientConnected(client: Client)
clientDisconnected(client: Client)
clientConnectionFailed(client: Client, error: SlackError)
connected(_ client: Client)
disconnected(_ client: Client)
connectionFailed(_ client: Client, error: SlackError)
```
##### MessageEventsDelegate
```swift
messageSent(client: Client, message: Message)
messageReceived(client: Client, message: Message)
messageChanged(client: Client, message: Message)
messageDeleted(client: Client, message: Message?)
sent(_ message: Message, client: Client)
received(_ message: Message, client: Client)
changed(_ message: Message, client: Client)
deleted(_ message: Message?, client: Client)
```
##### ChannelEventsDelegate
```swift
userTyping(client: Client, channel: Channel, user: User)
channelMarked(client: Client, channel: Channel, timestamp: String)
channelCreated(client: Client, channel: Channel)
channelDeleted(client: Client, channel: Channel)
channelRenamed(client: Client, channel: Channel)
channelArchived(client: Client, channel: Channel)
channelHistoryChanged(client: Client, channel: Channel)
channelJoined(client: Client, channel: Channel)
channelLeft(client: Client, channel: Channel)
userTypingIn(_ channel: Channel, user: User, client: Client)
marked(_ channel: Channel, timestamp: String, client: Client)
created(_ channel: Channel, client: Client)
deleted(_ channel: Channel, client: Client)
renamed(_ channel: Channel, client: Client)
archived(_ channel: Channel, client: Client)
historyChanged(_ channel: Channel, client: Client)
joined(_ channel: Channel, client: Client)
left(_ channel: Channel, client: Client)
```
##### DoNotDisturbEventsDelegate
```swift
doNotDisturbUpdated(client: Client, dndStatus: DoNotDisturbStatus)
doNotDisturbUserUpdated(client: Client, dndStatus: DoNotDisturbStatus, user: User)
updated(_ status: DoNotDisturbStatus, client: Client)
userUpdated(_ status: DoNotDisturbStatus, user: User, client: Client)
```
##### GroupEventsDelegate
```swift
groupOpened(client: Client, group: Channel)
opened(_ group: Channel, client: Client)
```
##### FileEventsDelegate
```swift
fileProcessed(client: Client, file: File)
fileMadePrivate(client: Client, file: File)
fileDeleted(client: Client, file: File)
fileCommentAdded(client: Client, file: File, comment: Comment)
fileCommentEdited(client: Client, file: File, comment: Comment)
fileCommentDeleted(client: Client, file: File, comment: Comment)
processed(_ file: File, client: Client)
madePrivate(_ file: File, client: Client)
deleted(_ file: File, client: Client)
commentAdded(_ file: File, comment: Comment, client: Client)
commentEdited(_ file: File, comment: Comment, client: Client)
commentDeleted(_ file: File, comment: Comment, client: Client)
```
##### PinEventsDelegate
```swift
itemPinned(client: Client, item: Item, channel: Channel?)
itemUnpinned(client: Client, item: Item, channel: Channel?)
pinned(_ item: Item, channel: Channel?, client: Client)
unpinned(_ item: Item, channel: Channel?, client: Client)
```
##### StarEventsDelegate
```swift
itemStarred(client: Client, item: Item, star: Bool)
starred(_ item: Item, starred: Bool, _ client: Client)
```
##### ReactionEventsDelegate
```swift
reactionAdded(client: Client, reaction: String, item: Item, itemUser: String)
reactionRemoved(client: Client, reaction: String, item: Item, itemUser: String)
added(_ reaction: String, item: Item, itemUser: String, client: Client)
removed(_ reaction: String, item: Item, itemUser: String, client: Client)
```
##### SlackEventsDelegate
```swift
preferenceChanged(client: Client, preference: String, value: AnyObject?)
userChanged(client: Client, user: User)
presenceChanged(client: Client, user: User, presence: String)
manualPresenceChanged(client: Client, user: User, presence: String)
botEvent(client: Client, bot: Bot)
preferenceChanged(_ preference: String, value: Any?, client: Client)
userChanged(_ user: User, client: Client)
presenceChanged(_ user: User, presence: String, client: Client)
manualPresenceChanged(_ user: User, presence: String, client: Client)
botEvent(_ bot: Bot, client: Client)
```
##### TeamEventsDelegate
```swift
teamJoined(client: Client, user: User)
teamPlanChanged(client: Client, plan: String)
teamPreferencesChanged(client: Client, preference: String, value: AnyObject?)
teamNameChanged(client: Client, name: String)
teamDomainChanged(client: Client, domain: String)
teamEmailDomainChanged(client: Client, domain: String)
teamEmojiChanged(client: Client)
userJoined(_ user: User, client: Client)
planChanged(_ plan: String, client: Client)
preferencesChanged(_ preference: String, value: Any?, client: Client)
nameChanged(_ name: String, client: Client)
domainChanged(_ domain: String, client: Client)
emailDomainChanged(_ domain: String, client: Client)
emojiChanged(_ client: Client)
```
##### SubteamEventsDelegate
```swift
subteamEvent(client: Client, userGroup: UserGroup)
subteamSelfAdded(client: Client, subteamID: String)
subteamSelfRemoved(client: Client, subteamID: String)
event(_ userGroup: UserGroup, client: Client)
selfAdded(_ subteamID: String, client: Client)
selfRemoved(_ subteamID: String, client: Client)
```
##### TeamProfileEventsDelegate
```swift
teamProfileChanged(client: Client, profile: CustomProfile)
teamProfileDeleted(client: Client, profile: CustomProfile)
teamProfileReordered(client: Client, profile: CustomProfile)
changed(_ profile: CustomProfile, client: Client)
deleted(_ profile: CustomProfile, client: Client)
reordered(_ profile: CustomProfile, client: Client)
```
### Examples
+2 -3
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = "SlackKit"
s.version = "2.0.0"
s.version = "3.1.7"
s.summary = "a Slack client library for OS X, iOS, and tvOS written in Swift"
s.homepage = "https://github.com/pvzig/SlackKit"
s.license = 'MIT'
@@ -13,7 +13,6 @@ Pod::Spec.new do |s|
s.requires_arc = true
s.source_files = 'SlackKit/Sources/*.swift'
s.frameworks = 'Foundation'
s.dependency 'Starscream', '~> 1.1.3'
s.dependency 'Starscream'
s.dependency 'Swifter'
end
+37 -17
View File
@@ -30,7 +30,6 @@
263993A71CE90EE0004A6E93 /* Client+EventHandling.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A85FF81CE3BCEF00756C40 /* Client+EventHandling.swift */; };
263993A81CE90EE0004A6E93 /* NetworkInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 260EC2311C4DC61D0093B253 /* NetworkInterface.swift */; };
263993A91CE90EE0004A6E93 /* EventDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26BBA18B1C398E3C00BF7225 /* EventDelegate.swift */; };
263993AB1CE90EE0004A6E93 /* Starscream.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4307A07F1CC6D0910011D5DE /* Starscream.framework */; };
263993AD1CE90EE0004A6E93 /* SlackKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 2661A6A41BBF62FF0026F67B /* SlackKit.h */; settings = {ATTRIBUTES = (Public, ); }; };
263993B61CE90EED004A6E93 /* Client+Utilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = C16C98791CE7D3DD00692776 /* Client+Utilities.swift */; };
263993B71CE90EED004A6E93 /* Channel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26BBA1881C398E3C00BF7225 /* Channel.swift */; };
@@ -50,8 +49,13 @@
263993C61CE90EED004A6E93 /* Client+EventHandling.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A85FF81CE3BCEF00756C40 /* Client+EventHandling.swift */; };
263993C71CE90EED004A6E93 /* NetworkInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 260EC2311C4DC61D0093B253 /* NetworkInterface.swift */; };
263993C81CE90EED004A6E93 /* EventDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26BBA18B1C398E3C00BF7225 /* EventDelegate.swift */; };
263993CA1CE90EED004A6E93 /* Starscream.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4307A07F1CC6D0910011D5DE /* Starscream.framework */; };
263993CC1CE90EED004A6E93 /* SlackKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 2661A6A41BBF62FF0026F67B /* SlackKit.h */; settings = {ATTRIBUTES = (Public, ); }; };
2659FC1B1DADC4E0003F3930 /* Starscream.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4307A07F1CC6D0910011D5DE /* Starscream.framework */; };
2659FC1C1DADC4E0003F3930 /* Swifter.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 26B30B6B1D289FA0004D4AB5 /* Swifter.framework */; };
2659FC1D1DADC4F2003F3930 /* Swifter.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 26B30B6E1D289FB2004D4AB5 /* Swifter.framework */; };
2659FC1F1DADC4F2003F3930 /* Starscream.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2659FC1E1DADC4F2003F3930 /* Starscream.framework */; };
2659FC201DADC4FC003F3930 /* Swifter.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 269B47CB1D3AE5670042D137 /* Swifter.framework */; };
2659FC221DADC4FC003F3930 /* Starscream.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2659FC211DADC4FC003F3930 /* Starscream.framework */; };
2678B5941D3151B900CE521A /* AuthorizeResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2678B5931D3151B900CE521A /* AuthorizeResponse.swift */; };
2678B5951D3151B900CE521A /* AuthorizeResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2678B5931D3151B900CE521A /* AuthorizeResponse.swift */; };
2678B5961D3151B900CE521A /* AuthorizeResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2678B5931D3151B900CE521A /* AuthorizeResponse.swift */; };
@@ -74,12 +78,9 @@
269B47C81D3AE25B0042D137 /* MessageActionServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26B30B8F1D298E08004D4AB5 /* MessageActionServer.swift */; };
269B47C91D3AE2620042D137 /* Server.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26B30B911D298E12004D4AB5 /* Server.swift */; };
269B47CA1D3AE2670042D137 /* WebhookServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26EC15001D260B1000FD3A53 /* WebhookServer.swift */; };
269B47CC1D3AE5670042D137 /* Swifter.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 269B47CB1D3AE5670042D137 /* Swifter.framework */; };
269B47CE1D3C22FC0042D137 /* ClientOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 269B47CD1D3C22FC0042D137 /* ClientOptions.swift */; };
269B47CF1D3C22FC0042D137 /* ClientOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 269B47CD1D3C22FC0042D137 /* ClientOptions.swift */; };
269B47D01D3C22FC0042D137 /* ClientOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 269B47CD1D3C22FC0042D137 /* ClientOptions.swift */; };
26B30B6C1D289FA0004D4AB5 /* Swifter.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 26B30B6B1D289FA0004D4AB5 /* Swifter.framework */; };
26B30B6F1D289FB2004D4AB5 /* Swifter.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 26B30B6E1D289FB2004D4AB5 /* Swifter.framework */; };
26B30B881D297A98004D4AB5 /* MessageActionRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26B30B871D297A98004D4AB5 /* MessageActionRequest.swift */; };
26B30B901D298E08004D4AB5 /* MessageActionServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26B30B8F1D298E08004D4AB5 /* MessageActionServer.swift */; };
26B30B921D298E12004D4AB5 /* Server.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26B30B911D298E12004D4AB5 /* Server.swift */; };
@@ -147,7 +148,6 @@
26EC14FB1D1F355A00FD3A53 /* Action.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26EC14F81D1F355A00FD3A53 /* Action.swift */; };
26EC15011D260B1000FD3A53 /* WebhookServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26EC15001D260B1000FD3A53 /* WebhookServer.swift */; };
26EC15021D260B1000FD3A53 /* WebhookServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26EC15001D260B1000FD3A53 /* WebhookServer.swift */; };
4307A0801CC6D0910011D5DE /* Starscream.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4307A07F1CC6D0910011D5DE /* Starscream.framework */; };
C16C987A1CE7D3DD00692776 /* Client+Utilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = C16C98791CE7D3DD00692776 /* Client+Utilities.swift */; };
C1A85FF91CE3BCEF00756C40 /* Client+EventDispatching.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A85FF71CE3BCEF00756C40 /* Client+EventDispatching.swift */; };
C1A85FFA1CE3BCEF00756C40 /* Client+EventHandling.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A85FF81CE3BCEF00756C40 /* Client+EventHandling.swift */; };
@@ -161,6 +161,8 @@
260EC2321C4DC61D0093B253 /* WebAPI.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = WebAPI.swift; path = Sources/WebAPI.swift; sourceTree = "<group>"; };
263993B21CE90EE0004A6E93 /* SlackKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SlackKit.framework; sourceTree = BUILT_PRODUCTS_DIR; };
263993D11CE90EED004A6E93 /* SlackKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SlackKit.framework; sourceTree = BUILT_PRODUCTS_DIR; };
2659FC1E1DADC4F2003F3930 /* Starscream.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Starscream.framework; path = Carthage/Build/iOS/Starscream.framework; sourceTree = "<group>"; };
2659FC211DADC4FC003F3930 /* Starscream.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Starscream.framework; path = Carthage/Build/tvOS/Starscream.framework; sourceTree = "<group>"; };
2661A6A41BBF62FF0026F67B /* SlackKit.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SlackKit.h; sourceTree = "<group>"; };
2678B5931D3151B900CE521A /* AuthorizeResponse.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = AuthorizeResponse.swift; path = Sources/AuthorizeResponse.swift; sourceTree = "<group>"; };
268E46131CE8F79D009F19CC /* Info-iOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = "Info-iOS.plist"; path = "Supporting Files/Info-iOS.plist"; sourceTree = "<group>"; };
@@ -217,8 +219,8 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
4307A0801CC6D0910011D5DE /* Starscream.framework in Frameworks */,
26B30B6C1D289FA0004D4AB5 /* Swifter.framework in Frameworks */,
2659FC1B1DADC4E0003F3930 /* Starscream.framework in Frameworks */,
2659FC1C1DADC4E0003F3930 /* Swifter.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -226,8 +228,8 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
263993AB1CE90EE0004A6E93 /* Starscream.framework in Frameworks */,
26B30B6F1D289FB2004D4AB5 /* Swifter.framework in Frameworks */,
2659FC1F1DADC4F2003F3930 /* Starscream.framework in Frameworks */,
2659FC1D1DADC4F2003F3930 /* Swifter.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -235,8 +237,8 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
263993CA1CE90EED004A6E93 /* Starscream.framework in Frameworks */,
269B47CC1D3AE5670042D137 /* Swifter.framework in Frameworks */,
2659FC221DADC4FC003F3930 /* Starscream.framework in Frameworks */,
2659FC201DADC4FC003F3930 /* Swifter.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -353,6 +355,8 @@
CA70A3A1A9A1A259960DFBCF /* Frameworks */ = {
isa = PBXGroup;
children = (
2659FC211DADC4FC003F3930 /* Starscream.framework */,
2659FC1E1DADC4F2003F3930 /* Starscream.framework */,
269B47CB1D3AE5670042D137 /* Swifter.framework */,
26B30B6E1D289FB2004D4AB5 /* Swifter.framework */,
26B30B6B1D289FA0004D4AB5 /* Swifter.framework */,
@@ -452,11 +456,12 @@
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0730;
LastUpgradeCheck = 0730;
LastUpgradeCheck = 0800;
ORGANIZATIONNAME = "Launch Software LLC";
TargetAttributes = {
26072A331BB48B3A00CD650C = {
CreatedOnToolsVersion = 7.0;
LastSwiftMigration = 0800;
};
};
};
@@ -677,8 +682,10 @@
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
@@ -724,8 +731,10 @@
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
@@ -754,7 +763,7 @@
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_IDENTITY = "-";
CODE_SIGN_IDENTITY = "";
COMBINE_HIDPI_IMAGES = YES;
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
@@ -773,6 +782,7 @@
PRODUCT_NAME = SlackKit;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
};
name = Debug;
};
@@ -780,7 +790,7 @@
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_IDENTITY = "-";
CODE_SIGN_IDENTITY = "";
COMBINE_HIDPI_IMAGES = YES;
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
@@ -798,6 +808,8 @@
PRODUCT_BUNDLE_IDENTIFIER = com.launchsoft.SlackKit;
PRODUCT_NAME = SlackKit;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
SWIFT_VERSION = 3.0;
};
name = Release;
};
@@ -806,6 +818,7 @@
buildSettings = {
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "";
COMBINE_HIDPI_IMAGES = YES;
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
@@ -814,7 +827,6 @@
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Carthage/Build/iOS",
"$(PROJECT_DIR)/Carthage/Build/Mac",
);
FRAMEWORK_VERSION = A;
INFOPLIST_FILE = "$(SRCROOT)/SlackKit/Supporting Files/Info-iOS.plist";
@@ -828,6 +840,7 @@
SKIP_INSTALL = YES;
SUPPORTED_PLATFORMS = "iphonesimulator iphoneos";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
};
name = Debug;
};
@@ -836,6 +849,7 @@
buildSettings = {
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "";
COMBINE_HIDPI_IMAGES = YES;
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
@@ -844,7 +858,6 @@
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Carthage/Build/iOS",
"$(PROJECT_DIR)/Carthage/Build/Mac",
);
FRAMEWORK_VERSION = A;
INFOPLIST_FILE = "$(SRCROOT)/SlackKit/Supporting Files/Info-iOS.plist";
@@ -857,6 +870,8 @@
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
SUPPORTED_PLATFORMS = "iphonesimulator iphoneos";
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
SWIFT_VERSION = 3.0;
};
name = Release;
};
@@ -864,6 +879,7 @@
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
"CODE_SIGN_IDENTITY[sdk=appletvos*]" = "";
COMBINE_HIDPI_IMAGES = YES;
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
@@ -884,6 +900,7 @@
SKIP_INSTALL = YES;
SUPPORTED_PLATFORMS = "appletvsimulator appletvos";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
TVOS_DEPLOYMENT_TARGET = 9.0;
};
name = Debug;
@@ -892,6 +909,7 @@
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
"CODE_SIGN_IDENTITY[sdk=appletvos*]" = "";
COMBINE_HIDPI_IMAGES = YES;
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
@@ -911,6 +929,8 @@
SDKROOT = appletvos;
SKIP_INSTALL = YES;
SUPPORTED_PLATFORMS = "appletvsimulator appletvos";
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
SWIFT_VERSION = 3.0;
TVOS_DEPLOYMENT_TARGET = 9.0;
};
name = Release;
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0730"
LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0730"
LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0730"
LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
+15 -16
View File
@@ -30,16 +30,16 @@ public struct Action {
public let style: ActionStyle?
public let confirm: Confirm?
internal init(action:[String: AnyObject]?) {
internal init(action:[String: Any]?) {
name = action?["name"] as? String
text = action?["text"] as? String
type = action?["type"] as? String
value = action?["value"] as? String
style = ActionStyle(rawValue: action?["style"] as? String ?? "")
confirm = Confirm(confirm:action?["confirm"] as? [String: AnyObject])
confirm = Confirm(confirm:action?["confirm"] as? [String: Any])
}
public init(name: String, text: String, style: ActionStyle = .Default, value: String? = nil, confirm: Confirm? = nil) {
public init(name: String, text: String, style: ActionStyle = .defaultStyle, value: String? = nil, confirm: Confirm? = nil) {
self.type = "button"
self.name = name
self.text = text
@@ -48,13 +48,14 @@ public struct Action {
self.confirm = confirm
}
internal func dictionary() -> [String: AnyObject] {
var dict = [String: AnyObject]()
internal var dictionary: [String: Any] {
var dict = [String: Any]()
dict["name"] = name
dict["text"] = text
dict["type"] = type
dict["value"] = value
dict["confirm"] = confirm?.dictionary()
dict["style"] = style?.rawValue
dict["confirm"] = confirm?.dictionary
return dict
}
@@ -65,7 +66,7 @@ public struct Action {
public let okText: String?
public let dismissText: String?
internal init(confirm:[String: AnyObject]?) {
internal init(confirm:[String: Any]?) {
title = confirm?["title"] as? String
text = confirm?["text"] as? String
okText = confirm?["ok_text"] as? String
@@ -79,26 +80,24 @@ public struct Action {
self.dismissText = dismissText
}
internal func dictionary() -> [String: AnyObject] {
var dict = [String: AnyObject]()
internal var dictionary: [String: Any] {
var dict = [String: Any]()
dict["title"] = title
dict["text"] = text
dict["ok_text"] = okText
dict["dismiss_text"] = dismissText
return dict
}
}
}
public enum ActionStyle: String {
case Default = "default"
case Primary = "primary"
case Danger = "danger"
case defaultStyle = "default"
case primary = "primary"
case danger = "danger"
}
public enum ResponseType: String {
case InChannel = "in_channel"
case Ephemeral = "ephemeral"
case inChannel = "in_channel"
case ephemeral = "ephemeral"
}
+10 -11
View File
@@ -42,7 +42,7 @@ public struct Attachment {
public let footerIcon: String?
public let ts: Int?
internal init(attachment: [String: AnyObject]?) {
internal init(attachment: [String: Any]?) {
fallback = attachment?["fallback"] as? String
callbackID = attachment?["callback_id"] as? String
type = attachment?["attachment_type"] as? String
@@ -59,8 +59,8 @@ public struct Attachment {
footer = attachment?["footer"] as? String
footerIcon = attachment?["footer_icon"] as? String
ts = attachment?["ts"] as? Int
fields = (attachment?["fields"] as? [[String: AnyObject]])?.map { AttachmentField(field: $0) }
actions = (attachment?["actions"] as? [[String: AnyObject]])?.map { Action(action: $0) }
fields = (attachment?["fields"] as? [[String: Any]])?.map { AttachmentField(field: $0) }
actions = (attachment?["actions"] as? [[String: Any]])?.map { Action(action: $0) }
}
public init(fallback: String, title:String, callbackID: String? = nil, type: String? = nil, colorHex: String? = nil, pretext: String? = nil, authorName: String? = nil, authorLink: String? = nil, authorIcon: String? = nil, titleLink: String? = nil, text: String? = nil, fields: [AttachmentField]? = nil, actions: [Action]? = nil, imageURL: String? = nil, thumbURL: String? = nil, footer: String? = nil, footerIcon:String? = nil, ts:Int? = nil) {
@@ -84,8 +84,8 @@ public struct Attachment {
self.ts = ts
}
internal func dictionary() -> [String: AnyObject] {
var attachment = [String: AnyObject]()
internal var dictionary: [String: Any] {
var attachment = [String: Any]()
attachment["fallback"] = fallback
attachment["callback_id"] = callbackID
attachment["attachment_type"] = type
@@ -97,8 +97,8 @@ public struct Attachment {
attachment["title"] = title
attachment["title_link"] = titleLink
attachment["text"] = text
attachment["fields"] = fields?.map{$0.dictionary()}
attachment["actions"] = actions?.map{$0.dictionary()}
attachment["fields"] = fields?.map{$0.dictionary}
attachment["actions"] = actions?.map{$0.dictionary}
attachment["image_url"] = imageURL
attachment["thumb_url"] = thumbURL
attachment["footer"] = footer
@@ -106,11 +106,10 @@ public struct Attachment {
attachment["ts"] = ts
return attachment
}
}
public enum AttachmentColor: String {
case Good = "good"
case Warning = "warning"
case Danger = "danger"
case good = "good"
case warning = "warning"
case danger = "danger"
}
+4 -5
View File
@@ -27,7 +27,7 @@ public struct AttachmentField {
public let value: String?
public let short: Bool?
internal init(field: [String: AnyObject]?) {
internal init(field: [String: Any]?) {
title = field?["title"] as? String
value = field?["value"] as? String
short = field?["short"] as? Bool
@@ -35,16 +35,15 @@ public struct AttachmentField {
public init(title:String, value:String, short: Bool? = nil) {
self.title = title
self.value = value.slackFormatEscaping()
self.value = value.slackFormatEscaping
self.short = short
}
internal func dictionary() -> [String: AnyObject] {
var field = [String: AnyObject]()
internal var dictionary: [String: Any] {
var field = [String: Any]()
field["title"] = title
field["value"] = value
field["short"] = short
return field
}
}
+4 -5
View File
@@ -29,9 +29,9 @@ internal struct AuthorizeRequest {
let state: String
let team: String?
var parameters: [String: AnyObject] {
var json = [String : AnyObject]()
json["scope"] = scope.map({$0.rawValue}).joinWithSeparator(",")
var parameters: [String: Any] {
var json = [String : Any]()
json["scope"] = scope.map({$0.rawValue}).joined(separator: ",")
json["state"] = state
json["team"] = team
return json
@@ -44,5 +44,4 @@ internal struct AuthorizeRequest {
self.state = state
self.team = team
}
}
}
+1 -1
View File
@@ -27,7 +27,7 @@ internal struct AuthorizeResponse {
let state: String
init?(queryParameters: [(String, String)]) {
guard let code = queryParameters.first?.1, state = queryParameters.last?.1 else {
guard let code = queryParameters.first?.1, let state = queryParameters.last?.1 else {
return nil
}
self.code = code
+4 -5
View File
@@ -26,17 +26,16 @@ public struct Bot {
public let id: String?
internal(set) public var botToken: String?
internal(set) public var name: String?
internal(set) public var icons: [String: AnyObject]?
internal(set) public var icons: [String: Any]?
internal init(bot: [String: AnyObject]?) {
internal init(bot: [String: Any]?) {
id = bot?["id"] as? String
name = bot?["name"] as? String
icons = bot?["icons"] as? [String: AnyObject]
icons = bot?["icons"] as? [String: Any]
}
internal init(botUser: [String: AnyObject]?) {
internal init(botUser: [String: Any]?) {
id = botUser?["bot_user_id"] as? String
botToken = botUser?["bot_access_token"] as? String
}
}
+5 -5
View File
@@ -49,7 +49,7 @@ public struct Channel {
internal(set) public var usersTyping = [String]()
internal(set) public var messages = [String: Message]()
internal init(channel: [String: AnyObject]?) {
internal init(channel: [String: Any]?) {
id = channel?["id"] as? String
name = channel?["name"] as? String
created = channel?["created"] as? Int
@@ -62,8 +62,8 @@ public struct Channel {
isUserDeleted = channel?["is_user_deleted"] as? Bool
user = channel?["user"] as? String
isOpen = channel?["is_open"] as? Bool
topic = Topic(topic: channel?["topic"] as? [String: AnyObject])
purpose = Topic(topic: channel?["purpose"] as? [String: AnyObject])
topic = Topic(topic: channel?["topic"] as? [String: Any])
purpose = Topic(topic: channel?["purpose"] as? [String: Any])
isMember = channel?["is_member"] as? Bool
lastRead = channel?["last_read"] as? String
unread = channel?["unread_count"] as? Int
@@ -71,8 +71,8 @@ public struct Channel {
hasPins = channel?["has_pins"] as? Bool
members = channel?["members"] as? [String]
if let latestMsgDictionary = channel?["latest"] as? [String: AnyObject] {
latest = Message(message: latestMsgDictionary)
if let latestMesssageDictionary = channel?["latest"] as? [String: Any] {
latest = Message(dictionary: latestMesssageDictionary)
} else {
latest = Message(ts: channel?["latest"] as? String)
}
+66 -70
View File
@@ -23,155 +23,151 @@
internal extension Client {
func dispatch(event: [String: AnyObject]) {
let event = Event(event: event)
guard let type = event.type else {
return
}
func dispatch(_ event: [String: Any]) {
let event = Event(event)
let type = event.type ?? .error
switch type {
case .Hello:
case .hello:
connected = true
connectionEventsDelegate?.clientConnected(self)
case .Ok:
connectionEventsDelegate?.connected(self)
case .ok:
messageSent(event)
case .Message:
case .message:
if (event.subtype != nil) {
messageDispatcher(event)
} else {
messageReceived(event)
}
case .UserTyping:
case .userTyping:
userTyping(event)
case .ChannelMarked, .IMMarked, .GroupMarked:
case .channelMarked, .imMarked, .groupMarked:
channelMarked(event)
case .ChannelCreated, .IMCreated:
case .channelCreated, .imCreated:
channelCreated(event)
case .ChannelJoined, .GroupJoined:
case .channelJoined, .groupJoined:
channelJoined(event)
case .ChannelLeft, .GroupLeft:
case .channelLeft, .groupLeft:
channelLeft(event)
case .ChannelDeleted:
case .channelDeleted:
channelDeleted(event)
case .ChannelRenamed, .GroupRename:
case .channelRenamed, .groupRename:
channelRenamed(event)
case .ChannelArchive, .GroupArchive:
case .channelArchive, .groupArchive:
channelArchived(event, archived: true)
case .ChannelUnarchive, .GroupUnarchive:
case .channelUnarchive, .groupUnarchive:
channelArchived(event, archived: false)
case .ChannelHistoryChanged, .IMHistoryChanged, .GroupHistoryChanged:
case .channelHistoryChanged, .imHistoryChanged, .groupHistoryChanged:
channelHistoryChanged(event)
case .DNDUpdated:
case .dndUpdated:
doNotDisturbUpdated(event)
case .DNDUpatedUser:
case .dndUpatedUser:
doNotDisturbUserUpdated(event)
case .IMOpen, .GroupOpen:
case .imOpen, .groupOpen:
open(event, open: true)
case .IMClose, .GroupClose:
case .imClose, .groupClose:
open(event, open: false)
case .FileCreated:
case .fileCreated:
processFile(event)
case .FileShared:
case .fileShared:
processFile(event)
case .FileUnshared:
case .fileUnshared:
processFile(event)
case .FilePublic:
case .filePublic:
processFile(event)
case .FilePrivate:
case .filePrivate:
filePrivate(event)
case .FileChanged:
case .fileChanged:
processFile(event)
case .FileDeleted:
case .fileDeleted:
deleteFile(event)
case .FileCommentAdded:
case .fileCommentAdded:
fileCommentAdded(event)
case .FileCommentEdited:
case .fileCommentEdited:
fileCommentEdited(event)
case .FileCommentDeleted:
case .fileCommentDeleted:
fileCommentDeleted(event)
case .PinAdded:
case .pinAdded:
pinAdded(event)
case .PinRemoved:
case .pinRemoved:
pinRemoved(event)
case .Pong:
case .pong:
pong(event)
case .PresenceChange:
case .presenceChange:
presenceChange(event)
case .ManualPresenceChange:
case .manualPresenceChange:
manualPresenceChange(event)
case .PrefChange:
case .prefChange:
changePreference(event)
case .UserChange:
case .userChange:
userChange(event)
case .TeamJoin:
case .teamJoin:
teamJoin(event)
case .StarAdded:
case .starAdded:
itemStarred(event, star: true)
case .StarRemoved:
case .starRemoved:
itemStarred(event, star: false)
case .ReactionAdded:
case .reactionAdded:
addedReaction(event)
case .ReactionRemoved:
case .reactionRemoved:
removedReaction(event)
case .EmojiChanged:
case .emojiChanged:
emojiChanged(event)
case .CommandsChanged:
case .commandsChanged:
// This functionality is only used by our web client.
// The other APIs required to support slash command metadata are currently unstable.
// Until they are released other clients should ignore this event.
break
case .TeamPlanChange:
case .teamPlanChange:
teamPlanChange(event)
case .TeamPrefChange:
case .teamPrefChange:
teamPreferenceChange(event)
case .TeamRename:
case .teamRename:
teamNameChange(event)
case .TeamDomainChange:
case .teamDomainChange:
teamDomainChange(event)
case .EmailDomainChange:
case .emailDomainChange:
emailDomainChange(event)
case .TeamProfileChange:
case .teamProfileChange:
teamProfileChange(event)
case .TeamProfileDelete:
case .teamProfileDelete:
teamProfileDeleted(event)
case .TeamProfileReorder:
case .teamProfileReorder:
teamProfileReordered(event)
case .BotAdded:
case .botAdded:
bot(event)
case .BotChanged:
case .botChanged:
bot(event)
case .AccountsChanged:
case .accountsChanged:
// The accounts_changed event is used by our web client to maintain a list of logged-in accounts.
// Other clients should ignore this event.
break
case .TeamMigrationStarted:
case .teamMigrationStarted:
connect(options: options ?? ClientOptions())
case .ReconnectURL:
case .reconnectURL:
// The reconnect_url event is currently unsupported and experimental.
break
case .SubteamCreated, .SubteamUpdated:
case .subteamCreated, .subteamUpdated:
subteam(event)
case .SubteamSelfAdded:
case .subteamSelfAdded:
subteamAddedSelf(event)
case.SubteamSelfRemoved:
case .subteamSelfRemoved:
subteamRemovedSelf(event)
case .Error:
case .error:
print("Error: \(event)")
break
}
}
func messageDispatcher(event:Event) {
guard let value = event.subtype, subtype = MessageSubtype(rawValue:value) else {
func messageDispatcher(_ event:Event) {
guard let value = event.subtype, let subtype = MessageSubtype(rawValue:value) else {
return
}
switch subtype {
case .MessageChanged:
case .messageChanged:
messageChanged(event)
case .MessageDeleted:
case .messageDeleted:
messageDeleted(event)
default:
messageReceived(event)
}
}
}
+148 -149
View File
@@ -26,254 +26,254 @@ import Foundation
internal extension Client {
//MARK: - Pong
func pong(event: Event) {
func pong(_ event: Event) {
pong = event.replyTo
}
//MARK: - Messages
func messageSent(event: Event) {
guard let reply = event.replyTo, message = sentMessages[NSNumber(double: reply).stringValue], channel = message.channel, ts = message.ts else {
func messageSent(_ event: Event) {
guard let reply = event.replyTo, let message = sentMessages[NSNumber(value: reply).stringValue], let channel = message.channel, let ts = message.ts else {
return
}
message.ts = event.ts
message.text = event.text
channels[channel]?.messages[ts] = message
messageEventsDelegate?.messageSent(self, message: message)
messageEventsDelegate?.sent(message, client: self)
}
func messageReceived(event: Event) {
guard let channel = event.channel, message = event.message, id = channel.id, ts = message.ts else {
func messageReceived(_ event: Event) {
guard let channel = event.channel, let message = event.message, let id = channel.id, let ts = message.ts else {
return
}
channels[id]?.messages[ts] = message
messageEventsDelegate?.messageReceived(self, message: message)
messageEventsDelegate?.received(message, client:self)
}
func messageChanged(event: Event) {
guard let id = event.channel?.id, nested = event.nestedMessage, ts = nested.ts else {
func messageChanged(_ event: Event) {
guard let id = event.channel?.id, let nested = event.nestedMessage, let ts = nested.ts else {
return
}
channels[id]?.messages[ts] = nested
messageEventsDelegate?.messageChanged(self, message: nested)
messageEventsDelegate?.changed(nested, client:self)
}
func messageDeleted(event: Event) {
guard let id = event.channel?.id, key = event.message?.deletedTs, message = channels[id]?.messages[key] else {
func messageDeleted(_ event: Event) {
guard let id = event.channel?.id, let key = event.message?.deletedTs, let message = channels[id]?.messages[key] else {
return
}
channels[id]?.messages.removeValueForKey(key)
messageEventsDelegate?.messageDeleted(self, message: message)
_ = channels[id]?.messages.removeValue(forKey: key)
messageEventsDelegate?.deleted(message, client:self)
}
//MARK: - Channels
func userTyping(event: Event) {
guard let channel = event.channel, channelID = channel.id, user = event.user, userID = user.id where
channels.indexForKey(channelID) != nil && !channels[channelID]!.usersTyping.contains(userID) else {
func userTyping(_ event: Event) {
guard let channel = event.channel, let channelID = channel.id, let user = event.user, let userID = user.id ,
channels.index(forKey: channelID) != nil && !channels[channelID]!.usersTyping.contains(userID) else {
return
}
channels[channelID]?.usersTyping.append(userID)
channelEventsDelegate?.userTyping(self, channel: channel, user: user)
channelEventsDelegate?.userTypingIn(channel, user: user, client: self)
let timeout = dispatch_time(DISPATCH_TIME_NOW, Int64(5.0 * Double(NSEC_PER_SEC)))
dispatch_after(timeout, dispatch_get_main_queue()) {
if let index = self.channels[channelID]?.usersTyping.indexOf(userID) {
self.channels[channelID]?.usersTyping.removeAtIndex(index)
let timeout = DispatchTime.now() + Double(Int64(5.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: timeout, execute: {
if let index = self.channels[channelID]?.usersTyping.index(of: userID) {
self.channels[channelID]?.usersTyping.remove(at: index)
}
}
})
}
func channelMarked(event: Event) {
guard let channel = event.channel, id = channel.id, timestamp = event.ts else {
func channelMarked(_ event: Event) {
guard let channel = event.channel, let id = channel.id, let timestamp = event.ts else {
return
}
channels[id]?.lastRead = event.ts
channelEventsDelegate?.channelMarked(self, channel: channel, timestamp: timestamp)
channelEventsDelegate?.marked(channel, timestamp: timestamp, client: self)
}
func channelCreated(event: Event) {
guard let channel = event.channel, id = channel.id else {
func channelCreated(_ event: Event) {
guard let channel = event.channel, let id = channel.id else {
return
}
channels[id] = channel
channelEventsDelegate?.channelCreated(self, channel: channel)
channelEventsDelegate?.created(channel, client: self)
}
func channelDeleted(event: Event) {
guard let channel = event.channel, id = channel.id else {
func channelDeleted(_ event: Event) {
guard let channel = event.channel, let id = channel.id else {
return
}
channels.removeValueForKey(id)
channelEventsDelegate?.channelDeleted(self, channel: channel)
channels.removeValue(forKey: id)
channelEventsDelegate?.deleted(channel, client: self)
}
func channelJoined(event: Event) {
guard let channel = event.channel, id = channel.id else {
func channelJoined(_ event: Event) {
guard let channel = event.channel, let id = channel.id else {
return
}
channels[id] = event.channel
channelEventsDelegate?.channelJoined(self, channel: channel)
channelEventsDelegate?.joined(channel, client: self)
}
func channelLeft(event: Event) {
guard let channel = event.channel, id = channel.id else {
func channelLeft(_ event: Event) {
guard let channel = event.channel, let id = channel.id else {
return
}
if let userID = authenticatedUser?.id, index = channels[id]?.members?.indexOf(userID) {
channels[id]?.members?.removeAtIndex(index)
if let userID = authenticatedUser?.id, let index = channels[id]?.members?.index(of: userID) {
channels[id]?.members?.remove(at: index)
}
channelEventsDelegate?.channelLeft(self, channel: channel)
channelEventsDelegate?.left(channel, client: self)
}
func channelRenamed(event: Event) {
guard let channel = event.channel, id = channel.id else {
func channelRenamed(_ event: Event) {
guard let channel = event.channel, let id = channel.id else {
return
}
channels[id]?.name = channel.name
channelEventsDelegate?.channelRenamed(self, channel: channel)
channelEventsDelegate?.renamed(channel, client: self)
}
func channelArchived(event: Event, archived: Bool) {
guard let channel = event.channel, id = channel.id else {
func channelArchived(_ event: Event, archived: Bool) {
guard let channel = event.channel, let id = channel.id else {
return
}
channels[id]?.isArchived = archived
channelEventsDelegate?.channelArchived(self, channel: channel)
channelEventsDelegate?.archived(channel, client: self)
}
func channelHistoryChanged(event: Event) {
func channelHistoryChanged(_ event: Event) {
guard let channel = event.channel else {
return
}
channelEventsDelegate?.channelHistoryChanged(self, channel: channel)
channelEventsDelegate?.historyChanged(channel, client: self)
}
//MARK: - Do Not Disturb
func doNotDisturbUpdated(event: Event) {
func doNotDisturbUpdated(_ event: Event) {
guard let dndStatus = event.dndStatus else {
return
}
authenticatedUser?.doNotDisturbStatus = dndStatus
doNotDisturbEventsDelegate?.doNotDisturbUpdated(self, dndStatus: dndStatus)
doNotDisturbEventsDelegate?.updated(dndStatus, client: self)
}
func doNotDisturbUserUpdated(event: Event) {
guard let dndStatus = event.dndStatus, user = event.user, id = user.id else {
func doNotDisturbUserUpdated(_ event: Event) {
guard let dndStatus = event.dndStatus, let user = event.user, let id = user.id else {
return
}
users[id]?.doNotDisturbStatus = dndStatus
doNotDisturbEventsDelegate?.doNotDisturbUserUpdated(self, dndStatus: dndStatus, user: user)
doNotDisturbEventsDelegate?.userUpdated(dndStatus, user: user, client: self)
}
//MARK: - IM & Group Open/Close
func open(event: Event, open: Bool) {
guard let channel = event.channel, id = channel.id else {
func open(_ event: Event, open: Bool) {
guard let channel = event.channel, let id = channel.id else {
return
}
channels[id]?.isOpen = open
groupEventsDelegate?.groupOpened(self, group: channel)
groupEventsDelegate?.opened(channel, client: self)
}
//MARK: - Files
func processFile(event: Event) {
guard let file = event.file, id = file.id else {
func processFile(_ event: Event) {
guard let file = event.file, let id = file.id else {
return
}
if let comment = file.initialComment, commentID = comment.id {
if let comment = file.initialComment, let commentID = comment.id {
if files[id]?.comments[commentID] == nil {
files[id]?.comments[commentID] = comment
}
}
files[id] = file
fileEventsDelegate?.fileProcessed(self, file: file)
fileEventsDelegate?.processed(file, client: self)
}
func filePrivate(event: Event) {
guard let file = event.file, id = file.id else {
func filePrivate(_ event: Event) {
guard let file = event.file, let id = file.id else {
return
}
files[id]?.isPublic = false
fileEventsDelegate?.fileMadePrivate(self, file: file)
fileEventsDelegate?.madePrivate(file, client: self)
}
func deleteFile(event: Event) {
guard let file = event.file, id = file.id else {
func deleteFile(_ event: Event) {
guard let file = event.file, let id = file.id else {
return
}
if files[id] != nil {
files.removeValueForKey(id)
files.removeValue(forKey: id)
}
fileEventsDelegate?.fileDeleted(self, file: file)
fileEventsDelegate?.deleted(file, client: self)
}
func fileCommentAdded(event: Event) {
guard let file = event.file, id = file.id, comment = event.comment, commentID = comment.id else {
func fileCommentAdded(_ event: Event) {
guard let file = event.file, let id = file.id, let comment = event.comment, let commentID = comment.id else {
return
}
files[id]?.comments[commentID] = comment
fileEventsDelegate?.fileCommentAdded(self, file: file, comment: comment)
fileEventsDelegate?.commentAdded(file, comment: comment, client: self)
}
func fileCommentEdited(event: Event) {
guard let file = event.file, id = file.id, comment = event.comment, commentID = comment.id else {
func fileCommentEdited(_ event: Event) {
guard let file = event.file, let id = file.id, let comment = event.comment, let commentID = comment.id else {
return
}
files[id]?.comments[commentID]?.comment = comment.comment
fileEventsDelegate?.fileCommentEdited(self, file: file, comment: comment)
fileEventsDelegate?.commentAdded(file, comment: comment, client: self)
}
func fileCommentDeleted(event: Event) {
guard let file = event.file, id = file.id, comment = event.comment, commentID = comment.id else {
func fileCommentDeleted(_ event: Event) {
guard let file = event.file, let id = file.id, let comment = event.comment, let commentID = comment.id else {
return
}
files[id]?.comments.removeValueForKey(commentID)
fileEventsDelegate?.fileCommentDeleted(self, file: file, comment: comment)
_ = files[id]?.comments.removeValue(forKey: commentID)
fileEventsDelegate?.commentDeleted(file, comment: comment, client: self)
}
//MARK: - Pins
func pinAdded(event: Event) {
guard let id = event.channelID, item = event.item else {
func pinAdded(_ event: Event) {
guard let id = event.channelID, let item = event.item else {
return
}
channels[id]?.pinnedItems.append(item)
pinEventsDelegate?.itemPinned(self, item: item, channel: channels[id])
pinEventsDelegate?.pinned(item, channel: channels[id], client: self)
}
func pinRemoved(event: Event) {
guard let id = event.channelID, item = event.item else {
func pinRemoved(_ event: Event) {
guard let id = event.channelID, let item = event.item else {
return
}
if let pins = channels[id]?.pinnedItems.filter({$0 != item}) {
channels[id]?.pinnedItems = pins
}
pinEventsDelegate?.itemUnpinned(self, item: item, channel: channels[id])
pinEventsDelegate?.unpinned(item, channel: channels[id], client: self)
}
//MARK: - Stars
func itemStarred(event: Event, star: Bool) {
guard let item = event.item, type = item.type else {
func itemStarred(_ event: Event, star: Bool) {
guard let item = event.item, let type = item.type else {
return
}
switch type {
@@ -287,18 +287,18 @@ internal extension Client {
break
}
starEventsDelegate?.itemStarred(self, item: item, star: star)
starEventsDelegate?.starred(item, starred: star, self)
}
func starMessage(item: Item, star: Bool) {
guard let message = item.message, ts = message.ts, channel = item.channel where channels[channel]?.messages[ts] != nil else {
func starMessage(_ item: Item, star: Bool) {
guard let message = item.message, let ts = message.ts, let channel = item.channel , channels[channel]?.messages[ts] != nil else {
return
}
channels[channel]?.messages[ts]?.isStarred = star
}
func starFile(item: Item, star: Bool) {
guard let file = item.file, id = file.id else {
func starFile(_ item: Item, star: Bool) {
guard let file = item.file, let id = file.id else {
return
}
@@ -314,22 +314,22 @@ internal extension Client {
}
}
func starComment(item: Item) {
guard let file = item.file, id = file.id, comment = item.comment, commentID = comment.id else {
func starComment(_ item: Item) {
guard let file = item.file, let id = file.id, let comment = item.comment, let commentID = comment.id else {
return
}
files[id]?.comments[commentID] = comment
}
//MARK: - Reactions
func addedReaction(event: Event) {
guard let item = event.item, type = item.type, reaction = event.reaction, userID = event.user?.id, itemUser = event.itemUser else {
func addedReaction(_ event: Event) {
guard let item = event.item, let type = item.type, let reaction = event.reaction, let userID = event.user?.id, let itemUser = event.itemUser else {
return
}
switch type {
case "message":
guard let channel = item.channel, ts = item.ts, message = channels[channel]?.messages[ts] else {
guard let channel = item.channel, let ts = item.ts, let message = channels[channel]?.messages[ts] else {
return
}
message.reactions.append(Reaction(name: reaction, user: userID))
@@ -339,7 +339,7 @@ internal extension Client {
}
files[id]?.reactions.append(Reaction(name: reaction, user: userID))
case "file_comment":
guard let id = item.file?.id, commentID = item.fileCommentID else {
guard let id = item.file?.id, let commentID = item.fileCommentID else {
return
}
files[id]?.comments[commentID]?.reactions.append(Reaction(name: reaction, user: userID))
@@ -347,27 +347,27 @@ internal extension Client {
break
}
reactionEventsDelegate?.reactionAdded(self, reaction: reaction, item: item, itemUser: itemUser)
reactionEventsDelegate?.added(reaction, item: item, itemUser: itemUser, client: self)
}
func removedReaction(event: Event) {
guard let item = event.item, type = item.type, key = event.reaction, userID = event.user?.id, itemUser = event.itemUser else {
func removedReaction(_ event: Event) {
guard let item = event.item, let type = item.type, let key = event.reaction, let userID = event.user?.id, let itemUser = event.itemUser else {
return
}
switch type {
case "message":
guard let channel = item.channel, ts = item.ts, message = channels[channel]?.messages[ts] else {
guard let channel = item.channel, let ts = item.ts, let message = channels[channel]?.messages[ts] else {
return
}
message.reactions = message.reactions.filter({$0.name != key && $0.user != userID})
case "file":
guard let itemFile = item.file, id = itemFile.id else {
guard let itemFile = item.file, let id = itemFile.id else {
return
}
files[id]?.reactions = files[id]!.reactions.filter({$0.name != key && $0.user != userID})
case "file_comment":
guard let id = item.file?.id, commentID = item.fileCommentID else {
guard let id = item.file?.id, let commentID = item.fileCommentID else {
return
}
files[id]?.comments[commentID]?.reactions = files[id]!.comments[commentID]!.reactions.filter({$0.name != key && $0.user != userID})
@@ -375,140 +375,140 @@ internal extension Client {
break
}
reactionEventsDelegate?.reactionRemoved(self, reaction: key, item: item, itemUser: itemUser)
reactionEventsDelegate?.removed(key, item: item, itemUser: itemUser, client: self)
}
//MARK: - Preferences
func changePreference(event: Event) {
func changePreference(_ event: Event) {
guard let name = event.name else {
return
}
authenticatedUser?.preferences?[name] = event.value
slackEventsDelegate?.preferenceChanged(self, preference: name, value: event.value)
slackEventsDelegate?.preferenceChanged(name, value: event.value, client: self)
}
//Mark: - User Change
func userChange(event: Event) {
guard let user = event.user, id = user.id else {
func userChange(_ event: Event) {
guard let user = event.user, let id = user.id else {
return
}
let preferences = users[id]?.preferences
users[id] = user
users[id]?.preferences = preferences
slackEventsDelegate?.userChanged(self, user: user)
slackEventsDelegate?.userChanged(user, client: self)
}
//MARK: - User Presence
func presenceChange(event: Event) {
guard let user = event.user, id = user.id, presence = event.presence else {
func presenceChange(_ event: Event) {
guard let user = event.user, let id = user.id, let presence = event.presence else {
return
}
users[id]?.presence = event.presence
slackEventsDelegate?.presenceChanged(self, user: user, presence: presence)
slackEventsDelegate?.presenceChanged(user, presence: presence, client: self)
}
//MARK: - Team
func teamJoin(event: Event) {
guard let user = event.user, id = user.id else {
func teamJoin(_ event: Event) {
guard let user = event.user, let id = user.id else {
return
}
users[id] = user
teamEventsDelegate?.teamJoined(self, user: user)
teamEventsDelegate?.userJoined(user, client: self)
}
func teamPlanChange(event: Event) {
func teamPlanChange(_ event: Event) {
guard let plan = event.plan else {
return
}
team?.plan = plan
teamEventsDelegate?.teamPlanChanged(self, plan: plan)
teamEventsDelegate?.planChanged(plan, client: self)
}
func teamPreferenceChange(event: Event) {
func teamPreferenceChange(_ event: Event) {
guard let name = event.name else {
return
}
team?.prefs?[name] = event.value
teamEventsDelegate?.teamPreferencesChanged(self, preference: name, value: event.value)
teamEventsDelegate?.preferencesChanged(name, value: event.value, client: self)
}
func teamNameChange(event: Event) {
func teamNameChange(_ event: Event) {
guard let name = event.name else {
return
}
team?.name = name
teamEventsDelegate?.teamNameChanged(self, name: name)
teamEventsDelegate?.nameChanged(name, client: self)
}
func teamDomainChange(event: Event) {
func teamDomainChange(_ event: Event) {
guard let domain = event.domain else {
return
}
team?.domain = domain
teamEventsDelegate?.teamDomainChanged(self, domain: domain)
teamEventsDelegate?.domainChanged(domain, client: self)
}
func emailDomainChange(event: Event) {
func emailDomainChange(_ event: Event) {
guard let domain = event.emailDomain else {
return
}
team?.emailDomain = domain
teamEventsDelegate?.teamEmailDomainChanged(self, domain: domain)
teamEventsDelegate?.emailDomainChanged(domain, client: self)
}
func emojiChanged(event: Event) {
teamEventsDelegate?.teamEmojiChanged(self)
func emojiChanged(_ event: Event) {
teamEventsDelegate?.emojiChanged(self)
}
//MARK: - Bots
func bot(event: Event) {
guard let bot = event.bot, id = bot.id else {
func bot(_ event: Event) {
guard let bot = event.bot, let id = bot.id else {
return
}
bots[id] = bot
slackEventsDelegate?.botEvent(self, bot: bot)
slackEventsDelegate?.botEvent(bot, client: self)
}
//MARK: - Subteams
func subteam(event: Event) {
guard let subteam = event.subteam, id = subteam.id else {
func subteam(_ event: Event) {
guard let subteam = event.subteam, let id = subteam.id else {
return
}
userGroups[id] = subteam
subteamEventsDelegate?.subteamEvent(self, userGroup: subteam)
subteamEventsDelegate?.event(subteam, client: self)
}
func subteamAddedSelf(event: Event) {
guard let subteamID = event.subteamID, _ = authenticatedUser?.userGroups else {
func subteamAddedSelf(_ event: Event) {
guard let subteamID = event.subteamID, let _ = authenticatedUser?.userGroups else {
return
}
authenticatedUser?.userGroups![subteamID] = subteamID
subteamEventsDelegate?.subteamSelfAdded(self, subteamID: subteamID)
subteamEventsDelegate?.selfAdded(subteamID, client: self)
}
func subteamRemovedSelf(event: Event) {
func subteamRemovedSelf(_ event: Event) {
guard let subteamID = event.subteamID else {
return
}
authenticatedUser?.userGroups?.removeValueForKey(subteamID)
subteamEventsDelegate?.subteamSelfRemoved(self, subteamID: subteamID)
_ = authenticatedUser?.userGroups?.removeValue(forKey: subteamID)
subteamEventsDelegate?.selfRemoved(subteamID, client: self)
}
//MARK: - Team Profiles
func teamProfileChange(event: Event) {
func teamProfileChange(_ event: Event) {
guard let profile = event.profile else {
return
}
@@ -519,10 +519,10 @@ internal extension Client {
}
}
teamProfileEventsDelegate?.teamProfileChanged(self, profile: profile)
teamProfileEventsDelegate?.changed(profile, client: self)
}
func teamProfileDeleted(event: Event) {
func teamProfileDeleted(_ event: Event) {
guard let profile = event.profile else {
return
}
@@ -533,10 +533,10 @@ internal extension Client {
}
}
teamProfileEventsDelegate?.teamProfileDeleted(self, profile: profile)
teamProfileEventsDelegate?.deleted(profile, client: self)
}
func teamProfileReordered(event: Event) {
func teamProfileReordered(_ event: Event) {
guard let profile = event.profile else {
return
}
@@ -547,17 +547,16 @@ internal extension Client {
}
}
teamProfileEventsDelegate?.teamProfileReordered(self, profile: profile)
teamProfileEventsDelegate?.reordered(profile, client: self)
}
//MARK: - Authenticated User
func manualPresenceChange(event: Event) {
guard let presence = event.presence, user = authenticatedUser else {
func manualPresenceChange(_ event: Event) {
guard let presence = event.presence, let user = authenticatedUser else {
return
}
authenticatedUser?.presence = presence
slackEventsDelegate?.manualPresenceChanged(self, user: user, presence: presence)
slackEventsDelegate?.manualPresenceChanged(user, presence: presence, client: self)
}
}
+14 -14
View File
@@ -21,43 +21,43 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public enum ClientError: ErrorType {
case ChannelDoesNotExist
case UserDoesNotExist
public enum ClientError: Error {
case channelDoesNotExist
case userDoesNotExist
}
public extension Client {
//MARK: - User & Channel
public func getChannelIDByName(name: String) throws -> String {
guard let id = channels.filter({$0.1.name == stripString(name)}).first?.0 else {
throw ClientError.ChannelDoesNotExist
public func getChannelIDWith(name: String) throws -> String {
guard let id = channels.filter({$0.1.name == strip(string:name)}).first?.0 else {
throw ClientError.channelDoesNotExist
}
return id
}
public func getUserIDByName(name: String) throws -> String {
guard let id = users.filter({$0.1.name == stripString(name)}).first?.0 else {
throw ClientError.UserDoesNotExist
public func getUserIDWith(name: String) throws -> String {
guard let id = users.filter({$0.1.name == strip(string:name)}).first?.0 else {
throw ClientError.userDoesNotExist
}
return id
}
public func getImIDForUserWithID(id: String, success: (imID: String?)->Void, failure: (error: SlackError)->Void) {
public func getImIDForUserWith(id: String, success: @escaping (_ imID: String?)->Void, failure: @escaping (SlackError)->Void) {
let ims = channels.filter{$0.1.isIM == true}
let channel = ims.filter{$0.1.user == id}.first
if let channel = channel {
success(imID: channel.0)
success(channel.0)
} else {
webAPI.openIM(id, success: success, failure: failure)
webAPI.openIM(userID: id, success: success, failure: failure)
}
}
//MARK: - Utilities
internal func stripString(string: String) -> String {
internal func strip(string: String) -> String {
var strippedString = string
if string[string.startIndex] == "@" || string[string.startIndex] == "#" {
strippedString = string.substringFromIndex(string.startIndex.advancedBy(1))
strippedString = string.substring(from: string.characters.index(string.startIndex, offsetBy: 1))
}
return strippedString
}
+61 -63
View File
@@ -44,7 +44,7 @@ public final class Client: WebSocketDelegate {
}
internal var webSocket: WebSocket?
private let pingPongQueue = dispatch_queue_create("com.launchsoft.SlackKit", DISPATCH_QUEUE_SERIAL)
private let pingPongQueue = DispatchQueue(label: "com.launchsoft.SlackKit")
internal var ping: Double?
internal var pong: Double?
internal var options: ClientOptions?
@@ -69,24 +69,23 @@ public final class Client: WebSocketDelegate {
self.token = apiToken
}
public func setAuthToken(token: String) {
public func setAuthToken(_ token: String) {
self.token = token
}
public func connect(options options: ClientOptions = ClientOptions()) {
public func connect(options: ClientOptions = ClientOptions()) {
self.options = options
webAPI.rtmStart(options.simpleLatest, noUnreads: options.noUnreads, mpimAware: options.mpimAware, success: {
(response) -> Void in
guard let socketURL = response["url"] as? String, url = NSURL(string: socketURL) else {
webAPI.rtmStart(simpleLatest: options.simpleLatest, noUnreads: options.noUnreads, mpimAware: options.mpimAware, success: {(response) in
guard let socketURL = response["url"] as? String, let url = URL(string: socketURL) else {
return
}
self.initialSetup(response)
self.initialSetup(JSON: response)
self.webSocket = WebSocket(url: url)
self.webSocket?.delegate = self
self.webSocket?.connect()
}, failure: {(error) -> Void in
self.connectionEventsDelegate?.clientConnectionFailed(self, error: error)
})
}, failure: {(error) in
self.connectionEventsDelegate?.connectionFailed(self, error: error)
})
}
public func disconnect() {
@@ -94,48 +93,47 @@ public final class Client: WebSocketDelegate {
}
//MARK: - RTM Message send
public func sendMessage(message: String, channelID: String) {
public func send(message: String, channelID: String) {
guard connected else { return }
if let data = try? formatMessageToSlackJsonString(msg: message, channel: channelID),
string = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
webSocket?.writeString(string)
if let data = try? format(message: message, channel: channelID), let string = String(data: data, encoding: String.Encoding.utf8) {
webSocket?.write(string: string)
}
}
private func formatMessageToSlackJsonString(message: (msg: String, channel: String)) throws -> NSData {
let json: [String: AnyObject] = [
"id": NSDate().slackTimestamp(),
private func format(message: String, channel: String) throws -> Data {
let json: [String: Any] = [
"id": Date().slackTimestamp,
"type": "message",
"channel": message.channel,
"text": message.msg.slackFormatEscaping()
"channel": channel,
"text": message.slackFormatEscaping
]
addSentMessage(json)
return try NSJSONSerialization.dataWithJSONObject(json, options: [])
return try JSONSerialization.data(withJSONObject: json, options: [])
}
private func addSentMessage(dictionary: [String: AnyObject]) {
private func addSentMessage(_ dictionary: [String: Any]) {
var message = dictionary
guard let id = message["id"] as? NSNumber else {
return
}
let ts = String(id)
message.removeValueForKey("id")
let ts = String(describing: id)
message.removeValue(forKey: "id")
message["ts"] = ts
message["user"] = self.authenticatedUser?.id
sentMessages[ts] = Message(message: message)
sentMessages[ts] = Message(dictionary: message)
}
//MARK: - RTM Ping
private func pingRTMServerAtInterval(interval: NSTimeInterval) {
let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(interval * Double(NSEC_PER_SEC)))
dispatch_after(delay, pingPongQueue, {
private func pingRTMServerAt(interval: TimeInterval) {
let delay = DispatchTime.now() + Double(Int64(interval * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
pingPongQueue.asyncAfter(deadline: delay, execute: {
guard self.connected && self.timeoutCheck() else {
self.disconnect()
return
}
self.sendRTMPing()
self.pingRTMServerAtInterval(interval)
self.pingRTMServerAt(interval: interval)
})
}
@@ -143,22 +141,21 @@ public final class Client: WebSocketDelegate {
guard connected else {
return
}
let json: [String: AnyObject] = [
"id": NSDate().slackTimestamp(),
"type": "ping",
let json: [String: Any] = [
"id": Date().slackTimestamp,
"type": "ping"
]
guard let data = try? NSJSONSerialization.dataWithJSONObject(json, options: []) else {
guard let data = try? JSONSerialization.data(withJSONObject: json, options: []) else {
return
}
let string = NSString(data: data, encoding: NSUTF8StringEncoding)
if let writePing = string as? String {
if let string = String(data: data, encoding: String.Encoding.utf8) {
ping = json["id"] as? Double
webSocket?.writeString(writePing)
webSocket?.write(string: string)
}
}
private func timeoutCheck() -> Bool {
if let pong = pong, ping = ping, timeout = options?.timeout {
if let pong = pong, let ping = ping, let timeout = options?.timeout {
if pong - ping < timeout {
return true
} else {
@@ -171,62 +168,64 @@ public final class Client: WebSocketDelegate {
}
//MARK: - Client setup
private func initialSetup(json: [String: AnyObject]) {
team = Team(team: json["team"] as? [String: AnyObject])
authenticatedUser = User(user: json["self"] as? [String: AnyObject])
authenticatedUser?.doNotDisturbStatus = DoNotDisturbStatus(status: json["dnd"] as? [String: AnyObject])
enumerateObjects(json["users"] as? Array) { (user) in self.addUser(user) }
enumerateObjects(json["channels"] as? Array) { (channel) in self.addChannel(channel) }
enumerateObjects(json["groups"] as? Array) { (group) in self.addChannel(group) }
enumerateObjects(json["mpims"] as? Array) { (mpim) in self.addChannel(mpim) }
enumerateObjects(json["ims"] as? Array) { (ims) in self.addChannel(ims) }
enumerateObjects(json["bots"] as? Array) { (bots) in self.addBot(bots) }
enumerateSubteams(json["subteams"] as? [String: AnyObject])
private func initialSetup(JSON: [String: Any]) {
team = Team(team: JSON["team"] as? [String: Any])
authenticatedUser = User(user: JSON["self"] as? [String: Any])
authenticatedUser?.doNotDisturbStatus = DoNotDisturbStatus(status: JSON["dnd"] as? [String: Any])
enumerateObjects(JSON["users"] as? Array) { (user) in self.addUser(user) }
enumerateObjects(JSON["channels"] as? Array) { (channel) in self.addChannel(channel) }
enumerateObjects(JSON["groups"] as? Array) { (group) in self.addChannel(group) }
enumerateObjects(JSON["mpims"] as? Array) { (mpim) in self.addChannel(mpim) }
enumerateObjects(JSON["ims"] as? Array) { (ims) in self.addChannel(ims) }
enumerateObjects(JSON["bots"] as? Array) { (bots) in self.addBot(bots) }
enumerateSubteams(JSON["subteams"] as? [String: Any])
}
private func addUser(aUser: [String: AnyObject]) {
private func addUser(_ aUser: [String: Any]) {
let user = User(user: aUser)
if let id = user.id {
users[id] = user
}
}
private func addChannel(aChannel: [String: AnyObject]) {
private func addChannel(_ aChannel: [String: Any]) {
let channel = Channel(channel: aChannel)
if let id = channel.id {
channels[id] = channel
}
}
private func addBot(aBot: [String: AnyObject]) {
private func addBot(_ aBot: [String: Any]) {
let bot = Bot(bot: aBot)
if let id = bot.id {
bots[id] = bot
}
}
private func enumerateSubteams(subteams: [String: AnyObject]?) {
private func enumerateSubteams(_ subteams: [String: Any]?) {
if let subteams = subteams {
if let all = subteams["all"] as? [[String: AnyObject]] {
if let all = subteams["all"] as? [[String: Any]] {
for item in all {
let u = UserGroup(userGroup: item)
self.userGroups[u.id!] = u
if let id = u.id {
self.userGroups[id] = u
}
}
}
if let auth = subteams["self"] as? [String] {
for item in auth {
authenticatedUser?.userGroups = [String: String]()
authenticatedUser?.userGroups![item] = item
authenticatedUser?.userGroups?[item] = item
}
}
}
}
// MARK: - Utilities
private func enumerateObjects(array: [AnyObject]?, initalizer: ([String: AnyObject])-> Void) {
private func enumerateObjects(_ array: [Any]?, initalizer: ([String: Any])-> Void) {
if let array = array {
for object in array {
if let dictionary = object as? [String: AnyObject] {
if let dictionary = object as? [String: Any] {
initalizer(dictionary)
}
}
@@ -236,7 +235,7 @@ public final class Client: WebSocketDelegate {
// MARK: - WebSocketDelegate
public func websocketDidConnect(socket: WebSocket) {
if let pingInterval = options?.pingInterval {
pingRTMServerAtInterval(pingInterval)
pingRTMServerAt(interval: pingInterval)
}
}
@@ -244,22 +243,21 @@ public final class Client: WebSocketDelegate {
connected = false
webSocket = nil
authenticatedUser = nil
connectionEventsDelegate?.clientDisconnected(self)
if let options = options where options.reconnect == true {
connectionEventsDelegate?.disconnected(self)
if let options = options, options.reconnect == true {
connect(options: options)
}
}
public func websocketDidReceiveMessage(socket: WebSocket, text: String) {
guard let data = text.dataUsingEncoding(NSUTF8StringEncoding) else {
guard let data = text.data(using: String.Encoding.utf8) else {
return
}
if let json = (try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)) as? [String: AnyObject] {
if let json = (try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)) as? [String: Any] {
dispatch(json)
}
}
public func websocketDidReceiveData(socket: WebSocket, data: NSData) {}
public func websocketDidReceiveData(socket: WebSocket, data: Data) {}
}
+3 -4
View File
@@ -28,11 +28,11 @@ public struct ClientOptions {
let simpleLatest: Bool?
let noUnreads: Bool?
let mpimAware: Bool?
let pingInterval: NSTimeInterval?
let timeout: NSTimeInterval?
let pingInterval: TimeInterval?
let timeout: TimeInterval?
let reconnect: Bool?
public init(simpleLatest: Bool? = nil, noUnreads: Bool? = nil, mpimAware: Bool? = nil, pingInterval: NSTimeInterval? = nil, timeout: NSTimeInterval? = nil, reconnect: Bool? = nil) {
public init(simpleLatest: Bool? = nil, noUnreads: Bool? = nil, mpimAware: Bool? = nil, pingInterval: TimeInterval? = nil, timeout: TimeInterval? = nil, reconnect: Bool? = nil) {
self.simpleLatest = simpleLatest
self.noUnreads = noUnreads
self.mpimAware = mpimAware
@@ -40,5 +40,4 @@ public struct ClientOptions {
self.timeout = timeout
self.reconnect = reconnect
}
}
+7 -8
View File
@@ -21,7 +21,8 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public struct Comment {
public struct Comment: Equatable {
public let id: String?
public let user: String?
internal(set) public var created: Int?
@@ -30,7 +31,7 @@ public struct Comment {
internal(set) public var stars: Int?
internal(set) public var reactions = [Reaction]()
internal init(comment:[String: AnyObject]?) {
internal init(comment:[String: Any]?) {
id = comment?["id"] as? String
created = comment?["created"] as? Int
user = comment?["user"] as? String
@@ -43,10 +44,8 @@ public struct Comment {
self.id = id
self.user = nil
}
}
extension Comment: Equatable {}
public func ==(lhs: Comment, rhs: Comment) -> Bool {
return lhs.id == rhs.id
public static func ==(lhs: Comment, rhs: Comment) -> Bool {
return lhs.id == rhs.id
}
}
+6 -6
View File
@@ -22,13 +22,14 @@
// THE SOFTWARE.
public struct CustomProfile {
internal(set) public var fields = [String: CustomProfileField]()
internal init(profile: [String: AnyObject]?) {
if let eventFields = profile?["fields"] as? [AnyObject] {
internal init(profile: [String: Any]?) {
if let eventFields = profile?["fields"] as? [Any] {
for field in eventFields {
var cpf: CustomProfileField?
if let fieldDictionary = field as? [String: AnyObject] {
if let fieldDictionary = field as? [String: Any] {
cpf = CustomProfileField(field: fieldDictionary)
} else {
cpf = CustomProfileField(id: field as? String)
@@ -38,13 +39,12 @@ public struct CustomProfile {
}
}
internal init(customFields: [String: AnyObject]?) {
internal init(customFields: [String: Any]?) {
if let customFields = customFields {
for key in customFields.keys {
let cpf = CustomProfileField(field: customFields[key] as? [String: AnyObject])
let cpf = CustomProfileField(field: customFields[key] as? [String: Any])
self.fields[key] = cpf
}
}
}
}
+3 -2
View File
@@ -22,6 +22,7 @@
// THE SOFTWARE.
public struct CustomProfileField {
internal(set) public var id: String?
internal(set) public var alt: String?
internal(set) public var value: String?
@@ -33,7 +34,7 @@ public struct CustomProfileField {
internal(set) public var possibleValues: [String]?
internal(set) public var type: String?
internal init(field: [String: AnyObject]?) {
internal init(field: [String: Any]?) {
id = field?["id"] as? String
alt = field?["alt"] as? String
value = field?["value"] as? String
@@ -50,7 +51,7 @@ public struct CustomProfileField {
self.id = id
}
internal mutating func updateProfileField(profile: CustomProfileField?) {
internal mutating func updateProfileField(_ profile: CustomProfileField?) {
id = profile?.id != nil ? profile?.id : id
alt = profile?.alt != nil ? profile?.alt : alt
value = profile?.value != nil ? profile?.value : value
+2 -2
View File
@@ -22,18 +22,18 @@
// THE SOFTWARE.
public struct DoNotDisturbStatus {
internal(set) public var enabled: Bool?
internal(set) public var nextDoNotDisturbStart: Int?
internal(set) public var nextDoNotDisturbEnd: Int?
internal(set) public var snoozeEnabled: Bool?
internal(set) public var snoozeEndtime: Int?
internal init(status: [String: AnyObject]?) {
internal init(status: [String: Any]?) {
enabled = status?["dnd_enabled"] as? Bool
nextDoNotDisturbStart = status?["next_dnd_start_ts"] as? Int
nextDoNotDisturbEnd = status?["next_dnd_end_ts"] as? Int
snoozeEnabled = status?["snooze_enabled"] as? Bool
snoozeEndtime = status?["snooze_endtime"] as? Int
}
}
+2 -1
View File
@@ -22,10 +22,11 @@
// THE SOFTWARE.
public struct Edited {
public let user: String?
public let ts: String?
internal init(edited:[String: AnyObject]?) {
internal init(edited:[String: Any]?) {
user = edited?["user"] as? String
ts = edited?["ts"] as? String
}
+110 -113
View File
@@ -22,107 +22,106 @@
// THE SOFTWARE.
internal enum EventType: String {
case Hello = "hello"
case Message = "message"
case UserTyping = "user_typing"
case ChannelMarked = "channel_marked"
case ChannelCreated = "channel_created"
case ChannelJoined = "channel_joined"
case ChannelLeft = "channel_left"
case ChannelDeleted = "channel_deleted"
case ChannelRenamed = "channel_rename"
case ChannelArchive = "channel_archive"
case ChannelUnarchive = "channel_unarchive"
case ChannelHistoryChanged = "channel_history_changed"
case DNDUpdated = "dnd_updated"
case DNDUpatedUser = "dnd_updated_user"
case IMCreated = "im_created"
case IMOpen = "im_open"
case IMClose = "im_close"
case IMMarked = "im_marked"
case IMHistoryChanged = "im_history_changed"
case GroupJoined = "group_joined"
case GroupLeft = "group_left"
case GroupOpen = "group_open"
case GroupClose = "group_close"
case GroupArchive = "group_archive"
case GroupUnarchive = "group_unarchive"
case GroupRename = "group_rename"
case GroupMarked = "group_marked"
case GroupHistoryChanged = "group_history_changed"
case FileCreated = "file_created"
case FileShared = "file_shared"
case FileUnshared = "file_unshared"
case FilePublic = "file_public"
case FilePrivate = "file_private"
case FileChanged = "file_change"
case FileDeleted = "file_deleted"
case FileCommentAdded = "file_comment_added"
case FileCommentEdited = "file_comment_edited"
case FileCommentDeleted = "file_comment_deleted"
case PinAdded = "pin_added"
case PinRemoved = "pin_removed"
case Pong = "pong"
case PresenceChange = "presence_change"
case ManualPresenceChange = "manual_presence_change"
case PrefChange = "pref_change"
case UserChange = "user_change"
case TeamJoin = "team_join"
case StarAdded = "star_added"
case StarRemoved = "star_removed"
case ReactionAdded = "reaction_added"
case ReactionRemoved = "reaction_removed"
case EmojiChanged = "emoji_changed"
case CommandsChanged = "commands_changed"
case TeamPlanChange = "team_plan_change"
case TeamPrefChange = "team_pref_change"
case TeamRename = "team_rename"
case TeamDomainChange = "team_domain_change"
case EmailDomainChange = "email_domain_change"
case TeamProfileChange = "team_profile_change"
case TeamProfileDelete = "team_profile_delete"
case TeamProfileReorder = "team_profile_reorder"
case BotAdded = "bot_added"
case BotChanged = "bot_changed"
case AccountsChanged = "accounts_changed"
case TeamMigrationStarted = "team_migration_started"
case ReconnectURL = "reconnect_url"
case SubteamCreated = "subteam_created"
case SubteamUpdated = "subteam_updated"
case SubteamSelfAdded = "subteam_self_added"
case SubteamSelfRemoved = "subteam_self_removed"
case Ok = "ok"
case Error = "error"
case hello = "hello"
case message = "message"
case userTyping = "user_typing"
case channelMarked = "channel_marked"
case channelCreated = "channel_created"
case channelJoined = "channel_joined"
case channelLeft = "channel_left"
case channelDeleted = "channel_deleted"
case channelRenamed = "channel_rename"
case channelArchive = "channel_archive"
case channelUnarchive = "channel_unarchive"
case channelHistoryChanged = "channel_history_changed"
case dndUpdated = "dnd_updated"
case dndUpatedUser = "dnd_updated_user"
case imCreated = "im_created"
case imOpen = "im_open"
case imClose = "im_close"
case imMarked = "im_marked"
case imHistoryChanged = "im_history_changed"
case groupJoined = "group_joined"
case groupLeft = "group_left"
case groupOpen = "group_open"
case groupClose = "group_close"
case groupArchive = "group_archive"
case groupUnarchive = "group_unarchive"
case groupRename = "group_rename"
case groupMarked = "group_marked"
case groupHistoryChanged = "group_history_changed"
case fileCreated = "file_created"
case fileShared = "file_shared"
case fileUnshared = "file_unshared"
case filePublic = "file_public"
case filePrivate = "file_private"
case fileChanged = "file_change"
case fileDeleted = "file_deleted"
case fileCommentAdded = "file_comment_added"
case fileCommentEdited = "file_comment_edited"
case fileCommentDeleted = "file_comment_deleted"
case pinAdded = "pin_added"
case pinRemoved = "pin_removed"
case pong = "pong"
case presenceChange = "presence_change"
case manualPresenceChange = "manual_presence_change"
case prefChange = "pref_change"
case userChange = "user_change"
case teamJoin = "team_join"
case starAdded = "star_added"
case starRemoved = "star_removed"
case reactionAdded = "reaction_added"
case reactionRemoved = "reaction_removed"
case emojiChanged = "emoji_changed"
case commandsChanged = "commands_changed"
case teamPlanChange = "team_plan_change"
case teamPrefChange = "team_pref_change"
case teamRename = "team_rename"
case teamDomainChange = "team_domain_change"
case emailDomainChange = "email_domain_change"
case teamProfileChange = "team_profile_change"
case teamProfileDelete = "team_profile_delete"
case teamProfileReorder = "team_profile_reorder"
case botAdded = "bot_added"
case botChanged = "bot_changed"
case accountsChanged = "accounts_changed"
case teamMigrationStarted = "team_migration_started"
case reconnectURL = "reconnect_url"
case subteamCreated = "subteam_created"
case subteamUpdated = "subteam_updated"
case subteamSelfAdded = "subteam_self_added"
case subteamSelfRemoved = "subteam_self_removed"
case ok = "ok"
case error = "error"
}
internal enum MessageSubtype: String {
case BotMessage = "bot_message"
case MeMessage = "me_message"
case MessageChanged = "message_changed"
case MessageDeleted = "message_deleted"
case ChannelJoin = "channel_join"
case ChannelLeave = "channel_leave"
case ChannelTopic = "channel_topic"
case ChannelPurpose = "channel_purpose"
case ChannelName = "channel_name"
case ChannelArchive = "channel_archive"
case ChannelUnarchive = "channel_unarchive"
case GroupJoin = "group_join"
case GroupLeave = "group_leave"
case GroupTopic = "group_topic"
case GroupPurpose = "group_purpose"
case GroupName = "group_name"
case GroupArchive = "group_archive"
case GroupUnarchive = "group_unarchive"
case FileShare = "file_share"
case FileComment = "file_comment"
case FileMention = "file_mention"
case PinnedItem = "pinned_item"
case UnpinnedItem = "unpinned_item"
case botMessage = "bot_message"
case meMessage = "me_message"
case messageChanged = "message_changed"
case messageDeleted = "message_deleted"
case channelJoin = "channel_join"
case channelLeave = "channel_leave"
case channelTopic = "channel_topic"
case channelPurpose = "channel_purpose"
case channelName = "channel_name"
case channelArchive = "channel_archive"
case channelUnarchive = "channel_unarchive"
case groupJoin = "group_join"
case groupLeave = "group_leave"
case groupTopic = "group_topic"
case groupPurpose = "group_purpose"
case groupName = "group_name"
case groupArchive = "group_archive"
case groupUnarchive = "group_unarchive"
case fileShare = "file_share"
case fileComment = "file_comment"
case fileMention = "file_mention"
case pinnedItem = "pinned_item"
case unpinnedItem = "unpinned_item"
}
internal struct Event {
internal class Event {
let type: EventType?
let ts: String?
let subtype: String?
@@ -137,14 +136,14 @@ internal struct Event {
let fileID: String?
let presence: String?
let name: String?
let value: AnyObject?
let value: Any?
let plan: String?
let url: String?
let domain: String?
let emailDomain: String?
let reaction: String?
let replyTo: Double?
let reactions: [[String: AnyObject]]?
let reactions: [[String: Any]]?
let edited: Edited?
let bot: Bot?
let channel: Channel?
@@ -160,7 +159,7 @@ internal struct Event {
let subteamID: String?
var profile: CustomProfile?
init(event:[String: AnyObject]) {
init(_ event:[String: Any]) {
type = EventType(rawValue: event["type"] as? String ?? "ok")
ts = event["ts"] as? String
subtype = event["subtype"] as? String
@@ -182,38 +181,36 @@ internal struct Event {
emailDomain = event["email_domain"] as? String
reaction = event["reaction"] as? String
replyTo = event["reply_to"] as? Double
reactions = event["reactions"] as? [[String: AnyObject]]
bot = Bot(bot: event["bot"] as? [String: AnyObject])
edited = Edited(edited:event["edited"] as? [String: AnyObject])
dndStatus = DoNotDisturbStatus(status: event["dnd_status"] as? [String: AnyObject])
reactions = event["reactions"] as? [[String: Any]]
bot = Bot(bot: event["bot"] as? [String: Any])
edited = Edited(edited:event["edited"] as? [String: Any])
dndStatus = DoNotDisturbStatus(status: event["dnd_status"] as? [String: Any])
itemUser = event["item_user"] as? String
item = Item(item: event["item"] as? [String: AnyObject])
subteam = UserGroup(userGroup: event["subteam"] as? [String: AnyObject])
item = Item(item: event["item"] as? [String: Any])
subteam = UserGroup(userGroup: event["subteam"] as? [String: Any])
subteamID = event["subteam_id"] as? String
message = Message(message: event)
nestedMessage = Message(message: event["message"] as? [String: AnyObject])
profile = CustomProfile(profile: event["profile"] as? [String: AnyObject])
message = Message(dictionary: event)
nestedMessage = Message(dictionary: event["message"] as? [String: Any])
profile = CustomProfile(profile: event["profile"] as? [String: Any])
file = File(id: event["file"] as? String)
// Comment, Channel, and User can come across as Strings or Dictionaries
if let commentDictionary = event["comment"] as? [String: AnyObject] {
if let commentDictionary = event["comment"] as? [String: Any] {
comment = Comment(comment: commentDictionary)
} else {
comment = Comment(id: event["comment"] as? String)
}
if let userDictionary = event["user"] as? [String: AnyObject] {
if let userDictionary = event["user"] as? [String: Any] {
user = User(user: userDictionary)
} else {
user = User(id: event["user"] as? String)
}
if let channelDictionary = event["channel"] as? [String: AnyObject] {
if let channelDictionary = event["channel"] as? [String: Any] {
channel = Channel(channel: channelDictionary)
} else {
channel = Channel(id: event["channel"] as? String)
}
}
}
+48 -48
View File
@@ -22,88 +22,88 @@
// THE SOFTWARE.
public protocol ConnectionEventsDelegate: class {
func clientConnected(client: Client)
func clientDisconnected(client: Client)
func clientConnectionFailed(client: Client, error: SlackError)
func connected(_ client: Client)
func disconnected(_ client: Client)
func connectionFailed(_ client: Client, error: SlackError)
}
public protocol MessageEventsDelegate: class {
func messageSent(client: Client, message: Message)
func messageReceived(client: Client, message: Message)
func messageChanged(client: Client, message: Message)
func messageDeleted(client: Client, message: Message?)
func sent(_ message: Message, client: Client)
func received(_ message: Message, client: Client)
func changed(_ message: Message, client: Client)
func deleted(_ message: Message?, client: Client)
}
public protocol ChannelEventsDelegate: class {
func userTyping(client: Client, channel: Channel, user: User)
func channelMarked(client: Client, channel: Channel, timestamp: String)
func channelCreated(client: Client, channel: Channel)
func channelDeleted(client: Client, channel: Channel)
func channelRenamed(client: Client, channel: Channel)
func channelArchived(client: Client, channel: Channel)
func channelHistoryChanged(client: Client, channel: Channel)
func channelJoined(client: Client, channel: Channel)
func channelLeft(client: Client, channel: Channel)
func userTypingIn(_ channel: Channel, user: User, client: Client)
func marked(_ channel: Channel, timestamp: String, client: Client)
func created(_ channel: Channel, client: Client)
func deleted(_ channel: Channel, client: Client)
func renamed(_ channel: Channel, client: Client)
func archived(_ channel: Channel, client: Client)
func historyChanged(_ channel: Channel, client: Client)
func joined(_ channel: Channel, client: Client)
func left(_ channel: Channel, client: Client)
}
public protocol DoNotDisturbEventsDelegate: class {
func doNotDisturbUpdated(client: Client, dndStatus: DoNotDisturbStatus)
func doNotDisturbUserUpdated(client: Client, dndStatus: DoNotDisturbStatus, user: User)
func updated(_ status: DoNotDisturbStatus, client: Client)
func userUpdated(_ status: DoNotDisturbStatus, user: User, client: Client)
}
public protocol GroupEventsDelegate: class {
func groupOpened(client: Client, group: Channel)
func opened(_ group: Channel, client: Client)
}
public protocol FileEventsDelegate: class {
func fileProcessed(client: Client, file: File)
func fileMadePrivate(client: Client, file: File)
func fileDeleted(client: Client, file: File)
func fileCommentAdded(client: Client, file: File, comment: Comment)
func fileCommentEdited(client: Client, file: File, comment: Comment)
func fileCommentDeleted(client: Client, file: File, comment: Comment)
func processed(_ file: File, client: Client)
func madePrivate(_ file: File, client: Client)
func deleted(_ file: File, client: Client)
func commentAdded(_ file: File, comment: Comment, client: Client)
func commentEdited(_ file: File, comment: Comment, client: Client)
func commentDeleted(_ file: File, comment: Comment, client: Client)
}
public protocol PinEventsDelegate: class {
func itemPinned(client: Client, item: Item, channel: Channel?)
func itemUnpinned(client: Client, item: Item, channel: Channel?)
func pinned(_ item: Item, channel: Channel?, client: Client)
func unpinned(_ item: Item, channel: Channel?, client: Client)
}
public protocol StarEventsDelegate: class {
func itemStarred(client: Client, item: Item, star: Bool)
func starred(_ item: Item, starred: Bool, _ client: Client)
}
public protocol ReactionEventsDelegate: class {
func reactionAdded(client: Client, reaction: String, item: Item, itemUser: String)
func reactionRemoved(client: Client, reaction: String, item: Item, itemUser: String)
func added(_ reaction: String, item: Item, itemUser: String, client: Client)
func removed(_ reaction: String, item: Item, itemUser: String, client: Client)
}
public protocol SlackEventsDelegate: class {
func preferenceChanged(client: Client, preference: String, value: AnyObject?)
func userChanged(client: Client, user: User)
func presenceChanged(client: Client, user: User, presence: String)
func manualPresenceChanged(client: Client, user: User, presence: String)
func botEvent(client: Client, bot: Bot)
func preferenceChanged(_ preference: String, value: Any?, client: Client)
func userChanged(_ user: User, client: Client)
func presenceChanged(_ user: User, presence: String, client: Client)
func manualPresenceChanged(_ user: User, presence: String, client: Client)
func botEvent(_ bot: Bot, client: Client)
}
public protocol TeamEventsDelegate: class {
func teamJoined(client: Client, user: User)
func teamPlanChanged(client: Client, plan: String)
func teamPreferencesChanged(client: Client, preference: String, value: AnyObject?)
func teamNameChanged(client: Client, name: String)
func teamDomainChanged(client: Client, domain: String)
func teamEmailDomainChanged(client: Client, domain: String)
func teamEmojiChanged(client: Client)
func userJoined(_ user: User, client: Client)
func planChanged(_ plan: String, client: Client)
func preferencesChanged(_ preference: String, value: Any?, client: Client)
func nameChanged(_ name: String, client: Client)
func domainChanged(_ domain: String, client: Client)
func emailDomainChanged(_ domain: String, client: Client)
func emojiChanged(_ client: Client)
}
public protocol SubteamEventsDelegate: class {
func subteamEvent(client: Client, userGroup: UserGroup)
func subteamSelfAdded(client: Client, subteamID: String)
func subteamSelfRemoved(client: Client, subteamID: String)
func event(_ userGroup: UserGroup, client: Client)
func selfAdded(_ subteamID: String, client: Client)
func selfRemoved(_ subteamID: String, client: Client)
}
public protocol TeamProfileEventsDelegate: class {
func teamProfileChanged(client: Client, profile: CustomProfile)
func teamProfileDeleted(client: Client, profile: CustomProfile)
func teamProfileReordered(client: Client, profile: CustomProfile)
func changed(_ profile: CustomProfile, client: Client)
func deleted(_ profile: CustomProfile, client: Client)
func reordered(_ profile: CustomProfile, client: Client)
}
+7 -27
View File
@@ -23,39 +23,19 @@
import Foundation
public extension NSDate {
public extension Date {
func slackTimestamp() -> Double {
return NSNumber(double: timeIntervalSince1970).doubleValue
var slackTimestamp: Double {
return NSNumber(value: timeIntervalSince1970).doubleValue
}
}
internal extension String {
func slackFormatEscaping() -> String {
var escapedString = stringByReplacingOccurrencesOfString("&", withString: "&amp;")
escapedString = stringByReplacingOccurrencesOfString("<", withString: "&lt;")
escapedString = stringByReplacingOccurrencesOfString(">", withString: "&gt;")
var slackFormatEscaping: String {
var escapedString = replacingOccurrences(of: "&", with: "&amp;")
escapedString = replacingOccurrences(of: "<", with: "&lt;")
escapedString = replacingOccurrences(of: ">", with: "&gt;")
return escapedString
}
}
internal extension Dictionary where Key: StringLiteralConvertible, Value: AnyObject {
var requestStringFromParameters: String {
var requestString = ""
for key in self.keys {
if let value = self[key] as? String, encodedValue = value.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet()) {
requestString += "&\(key)=\(encodedValue)"
} else if let value = self[key] as? Int {
requestString += "&\(key)=\(value)"
}
}
return requestString
}
}
+8 -11
View File
@@ -21,7 +21,7 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public struct File {
public struct File: Equatable {
public let id: String?
public let created: Int?
@@ -78,7 +78,7 @@ public struct File {
internal(set) public var comments = [String: Comment]()
internal(set) public var reactions = [Reaction]()
public init(file:[String: AnyObject]?) {
public init(file:[String: Any]?) {
id = file?["id"] as? String
created = file?["created"] as? Int
name = file?["name"] as? String
@@ -127,11 +127,11 @@ public struct File {
channels = file?["channels"] as? [String]
groups = file?["groups"] as? [String]
ims = file?["ims"] as? [String]
initialComment = Comment(comment: file?["initial_comment"] as? [String: AnyObject])
initialComment = Comment(comment: file?["initial_comment"] as? [String: Any])
stars = file?["num_stars"] as? Int
isStarred = file?["is_starred"] as? Bool
pinnedTo = file?["pinned_to"] as? [String]
reactions = Reaction.reactionsFromArray(file?["reactions"] as? [[String: AnyObject]])
reactions = Reaction.reactionsFromArray(file?["reactions"] as? [[String: Any]])
}
internal init(id:String?) {
@@ -179,11 +179,8 @@ public struct File {
linesMore = nil
initialComment = nil
}
public static func ==(lhs: File, rhs: File) -> Bool {
return lhs.id == rhs.id
}
}
extension File: Equatable {}
public func ==(lhs: File, rhs: File) -> Bool {
return lhs.id == rhs.id
}
+6 -6
View File
@@ -25,17 +25,17 @@ import Foundation
public struct History {
internal(set) public var latest: NSDate?
internal(set) public var latest: Date?
internal(set) public var messages = [Message]()
public let hasMore: Bool?
internal init(history: [String: AnyObject]?) {
if let latestStr = history?["latest"] as? String, latestDouble = Double(latestStr) {
latest = NSDate(timeIntervalSince1970: NSTimeInterval(latestDouble))
internal init(history: [String: Any]?) {
if let latestStr = history?["latest"] as? String, let latestDouble = Double(latestStr) {
latest = Date(timeIntervalSince1970: TimeInterval(latestDouble))
}
if let msgs = history?["messages"] as? [[String: AnyObject]] {
if let msgs = history?["messages"] as? [[String: Any]] {
for message in msgs {
messages.append(Message(message: message))
messages.append(Message(dictionary: message))
}
}
hasMore = history?["has_more"] as? Bool
+4 -5
View File
@@ -32,7 +32,7 @@ public struct IncomingWebhook {
public let iconEmoji: String?
public let iconURL: String?
internal init(webhook: [String: AnyObject]?) {
internal init(webhook: [String: Any]?) {
url = webhook?["url"] as? String
channel = webhook?["channel"] as? String
configurationURL = webhook?["configuration_url"] as? String
@@ -50,8 +50,8 @@ public struct IncomingWebhook {
self.configurationURL = nil
}
public func postMessage(response: Response, success: ((Bool)->Void)? = nil, failure: ((SlackError)->Void)? = nil) {
if let url = self.url, data = try? NSJSONSerialization.dataWithJSONObject(jsonBody(response.json()), options: []) {
public func postMessage(_ response: Response, success: ((Bool)->Void)? = nil, failure: ((SlackError)->Void)? = nil) {
if let url = self.url, let data = try? JSONSerialization.data(withJSONObject: jsonBody(response.json), options: []) {
NetworkInterface().customRequest(url, data: data, success: { _ in
success?(true)
}, errorClosure: {(error) in
@@ -60,7 +60,7 @@ public struct IncomingWebhook {
}
}
private func jsonBody(response: [String: AnyObject]) -> [String: AnyObject] {
private func jsonBody(_ response: [String: Any]) -> [String: Any] {
var json = response
json["channel"] = channel
json["username"] = username
@@ -68,5 +68,4 @@ public struct IncomingWebhook {
json["icon_url"] = iconURL
return json
}
}
+10 -12
View File
@@ -21,7 +21,8 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public struct Item {
public struct Item: Equatable {
public let type: String?
public let ts: String?
public let channel: String?
@@ -30,21 +31,20 @@ public struct Item {
public let comment: Comment?
public let fileCommentID: String?
internal init(item:[String: AnyObject]?) {
internal init(item:[String: Any]?) {
type = item?["type"] as? String
ts = item?["ts"] as? String
channel = item?["channel"] as? String
message = Message(message: item?["message"] as? [String: AnyObject])
message = Message(dictionary: item?["message"] as? [String: Any])
// Comment and File can come across as Strings or Dictionaries
if let commentDictionary = item?["comment"] as? [String: AnyObject] {
if let commentDictionary = item?["comment"] as? [String: Any] {
comment = Comment(comment: commentDictionary)
} else {
comment = Comment(id: item?["comment"] as? String)
}
if let fileDictionary = item?["file"] as? [String: AnyObject] {
if let fileDictionary = item?["file"] as? [String: Any] {
file = File(file: fileDictionary)
} else {
file = File(id: item?["file"] as? String)
@@ -52,10 +52,8 @@ public struct Item {
fileCommentID = item?["file_comment"] as? String
}
}
extension Item: Equatable {}
public func ==(lhs: Item, rhs: Item) -> Bool {
return lhs.type == rhs.type && lhs.channel == rhs.channel && lhs.file == rhs.file && lhs.comment == rhs.comment && lhs.message == rhs.message
public static func ==(lhs: Item, rhs: Item) -> Bool {
return lhs.type == rhs.type && lhs.channel == rhs.channel && lhs.file == rhs.file && lhs.comment == rhs.comment && lhs.message == rhs.message
}
}
+33 -36
View File
@@ -21,7 +21,7 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public final class Message {
public final class Message: Equatable {
public let type = "message"
public let subtype: String?
@@ -32,7 +32,7 @@ public final class Message {
internal(set) public var text: String?
public let botID: String?
public let username: String?
public let icons: [String: AnyObject]?
public let icons: [String: Any]?
public let deletedTs: String?
internal(set) var purpose: String?
internal(set) var topic: String?
@@ -51,33 +51,33 @@ public final class Message {
internal(set) public var replaceOriginal: Bool?
internal(set) public var deleteOriginal: Bool?
public init(message: [String: AnyObject]?) {
subtype = message?["subtype"] as? String
ts = message?["ts"] as? String
user = message?["user"] as? String
channel = message?["channel"] as? String
hidden = message?["hidden"] as? Bool
text = message?["text"] as? String
botID = message?["bot_id"] as? String
username = message?["username"] as? String
icons = message?["icons"] as? [String: AnyObject]
deletedTs = message?["deleted_ts"] as? String
purpose = message?["purpose"] as? String
topic = message?["topic"] as? String
name = message?["name"] as? String
members = message?["members"] as? [String]
oldName = message?["old_name"] as? String
upload = message?["upload"] as? Bool
itemType = message?["item_type"] as? String
isStarred = message?["is_starred"] as? Bool
pinnedTo = message?["pinned_to"] as? [String]
comment = Comment(comment: message?["comment"] as? [String: AnyObject])
file = File(file: message?["file"] as? [String: AnyObject])
reactions = Reaction.reactionsFromArray(message?["reactions"] as? [[String: AnyObject]])
attachments = (message?["attachments"] as? [[String: AnyObject]])?.map{Attachment(attachment: $0)}
responseType = ResponseType(rawValue: message?["response_type"] as? String ?? "")
replaceOriginal = message?["replace_original"] as? Bool
deleteOriginal = message?["delete_original"] as? Bool
public init(dictionary: [String: Any]?) {
subtype = dictionary?["subtype"] as? String
ts = dictionary?["ts"] as? String
user = dictionary?["user"] as? String
channel = dictionary?["channel"] as? String
hidden = dictionary?["hidden"] as? Bool
text = dictionary?["text"] as? String
botID = dictionary?["bot_id"] as? String
username = dictionary?["username"] as? String
icons = dictionary?["icons"] as? [String: Any]
deletedTs = dictionary?["deleted_ts"] as? String
purpose = dictionary?["purpose"] as? String
topic = dictionary?["topic"] as? String
name = dictionary?["name"] as? String
members = dictionary?["members"] as? [String]
oldName = dictionary?["old_name"] as? String
upload = dictionary?["upload"] as? Bool
itemType = dictionary?["item_type"] as? String
isStarred = dictionary?["is_starred"] as? Bool
pinnedTo = dictionary?["pinned_to"] as? [String]
comment = Comment(comment: dictionary?["comment"] as? [String: Any])
file = File(file: dictionary?["file"] as? [String: Any])
reactions = Reaction.reactionsFromArray(dictionary?["reactions"] as? [[String: Any]])
attachments = (dictionary?["attachments"] as? [[String: Any]])?.map{Attachment(attachment: $0)}
responseType = ResponseType(rawValue: dictionary?["response_type"] as? String ?? "")
replaceOriginal = dictionary?["replace_original"] as? Bool
deleteOriginal = dictionary?["delete_original"] as? Bool
}
internal init(ts:String?) {
@@ -94,11 +94,8 @@ public final class Message {
comment = nil
file = nil
}
}
extension Message: Equatable {}
public func ==(lhs: Message, rhs: Message) -> Bool {
return lhs.ts == rhs.ts && lhs.user == rhs.user && lhs.text == rhs.text
public static func ==(lhs: Message, rhs: Message) -> Bool {
return lhs.ts == rhs.ts && lhs.user == rhs.user && lhs.text == rhs.text
}
}
+6 -7
View File
@@ -35,18 +35,17 @@ internal struct MessageActionRequest: Request {
let originalMessage: Message?
let responseURL: String
init(response: [String: AnyObject]?) {
action = (response?["actions"] as? [[String:AnyObject]])?.map({Action(action: $0)}).first
init(response: [String: Any]?) {
action = (response?["actions"] as? [[String:Any]])?.map({Action(action: $0)}).first
callbackID = response?["callback_id"] as? String
team = Team(team: response?["team"] as? [String: AnyObject])
channel = Channel(channel: response?["channel"] as? [String: AnyObject])
user = User(user: response?["channel"] as? [String: AnyObject])
team = Team(team: response?["team"] as? [String: Any])
channel = Channel(channel: response?["channel"] as? [String: Any])
user = User(user: response?["channel"] as? [String: Any])
actionTS = response?["action_ts"] as? String
messageTS = response?["message_ts"] as? String
attachmentID = response?["attachment_id"] as? String
token = response?["token"] as? String
originalMessage = Message(message: response?["original_message"] as? [String: AnyObject])
originalMessage = Message(dictionary: response?["original_message"] as? [String: Any])
responseURL = response?["response_url"] as? String ?? ""
}
}
@@ -29,12 +29,11 @@ public struct MessageActionResponder {
self.responses = responses
}
internal func responseForRequest(request:MessageActionRequest) -> Reply? {
internal func responseForRequest(_ request:MessageActionRequest) -> Reply? {
if let response = responses.filter({$0.0.name == request.action?.name}).first?.1 {
return Reply.JSON(response: response)
return Reply.json(response: response)
} else {
return nil
}
}
}
+5 -6
View File
@@ -21,7 +21,7 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public class MessageActionServer: Server {
open class MessageActionServer: Server {
internal let responder: MessageActionResponder
@@ -31,16 +31,15 @@ public class MessageActionServer: Server {
addRoute(route)
}
internal func addRoute(route: String) {
internal func addRoute(_ route: String) {
http.POST["/\(route)"] = { request in
let payload = request.parseUrlencodedForm()
let actionRequest = MessageActionRequest(response: self.jsonFromRequest(payload[0].1))
if let reply = self.responder.responseForRequest(actionRequest) where actionRequest.token == self.token {
if let reply = self.responder.responseForRequest(actionRequest), actionRequest.token == self.token {
return self.request(actionRequest, reply: reply)
} else {
return .BadRequest(.Text("Bad request."))
return .badRequest(.text("Bad request."))
}
}
}
}
}
+71 -68
View File
@@ -27,121 +27,114 @@ internal struct NetworkInterface {
private let apiUrl = "https://slack.com/api/"
internal func request(endpoint: Endpoint, token: String? = nil, parameters: [String: AnyObject]?, successClosure: ([String: AnyObject])->Void, errorClosure: (SlackError)->Void) {
var requestString = "\(apiUrl)\(endpoint.rawValue)?"
if let token = token {
requestString += "token=\(token)"
internal func request(_ endpoint: Endpoint, parameters: [String: Any?], successClosure: @escaping ([String: Any])->Void, errorClosure: @escaping (SlackError)->Void) {
var components = URLComponents(string: "\(apiUrl)\(endpoint.rawValue)")
if parameters.count > 0 {
components?.queryItems = filterNilParameters(parameters).map { URLQueryItem(name: $0.0, value: "\($0.1)") }
}
if let params = parameters {
requestString += params.requestStringFromParameters
}
guard let url = NSURL(string: requestString) else {
errorClosure(SlackError.ClientNetworkError)
guard let url = components?.url else {
errorClosure(SlackError.clientNetworkError)
return
}
let request = NSURLRequest(URL:url)
NSURLSession.sharedSession().dataTaskWithRequest(request) {
(data, response, internalError) -> Void in
self.handleResponse(data, response: response, internalError: internalError, successClosure: {(json) in
successClosure(json)
}, errorClosure: {(error) in
errorClosure(error)
})
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) {(data, response, internalError) in
do {
successClosure(try self.handleResponse(data, response: response, internalError: internalError))
} catch let error {
errorClosure(error as? SlackError ?? SlackError.unknownError)
}
}.resume()
}
internal func customRequest(url: String, data: NSData, success: (Bool)->Void, errorClosure: (SlackError)->Void) {
guard let requestString = url.stringByRemovingPercentEncoding, url = NSURL(string: requestString) else {
errorClosure(SlackError.ClientNetworkError)
internal func customRequest(_ url: String, data: Data, success: @escaping (Bool)->Void, errorClosure: @escaping (SlackError)->Void) {
guard let url = URL(string: url.removePercentEncoding()) else {
errorClosure(SlackError.clientNetworkError)
return
}
let request = NSMutableURLRequest(URL:url)
request.HTTPMethod = "POST"
var request = URLRequest(url:url)
request.httpMethod = "POST"
let contentType = "application/json"
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
request.HTTPBody = data
request.httpBody = data
NSURLSession.sharedSession().dataTaskWithRequest(request) {
(data, response, internalError) -> Void in
URLSession.shared.dataTask(with: request) {(data, response, internalError) in
if internalError == nil {
success(true)
} else {
errorClosure(SlackError.ClientNetworkError)
errorClosure(SlackError.clientNetworkError)
}
}.resume()
}.resume()
}
internal func uploadRequest(token: String, data: NSData, parameters: [String: AnyObject]?, successClosure: ([String: AnyObject])->Void, errorClosure: (SlackError)->Void) {
var requestString = "\(apiUrl)\(Endpoint.FilesUpload.rawValue)?token=\(token)"
if let params = parameters {
requestString = requestString + params.requestStringFromParameters
internal func uploadRequest(data: Data, parameters: [String: Any?], successClosure: @escaping ([String: Any])->Void, errorClosure: @escaping (SlackError)->Void) {
var components = URLComponents(string: "\(apiUrl)\(Endpoint.filesUpload.rawValue)")
if parameters.count > 0 {
components?.queryItems = filterNilParameters(parameters).map { URLQueryItem(name: $0.0, value: "\($0.1)") }
}
guard let url = NSURL(string: requestString) else {
errorClosure(SlackError.ClientNetworkError)
guard let url = components?.url else {
errorClosure(SlackError.clientNetworkError)
return
}
let request = NSMutableURLRequest(URL:url)
request.HTTPMethod = "POST"
var request = URLRequest(url:url)
request.httpMethod = "POST"
let boundaryConstant = randomBoundary()
let contentType = "multipart/form-data; boundary=" + boundaryConstant
let boundaryStart = "--\(boundaryConstant)\r\n"
let boundaryEnd = "--\(boundaryConstant)--\r\n"
let contentDispositionString = "Content-Disposition: form-data; name=\"file\"; filename=\"\(parameters!["filename"])\"\r\n"
let contentTypeString = "Content-Type: \(parameters!["filetype"])\r\n\r\n"
let requestBodyData : NSMutableData = NSMutableData()
requestBodyData.appendData(boundaryStart.dataUsingEncoding(NSUTF8StringEncoding)!)
requestBodyData.appendData(contentDispositionString.dataUsingEncoding(NSUTF8StringEncoding)!)
requestBodyData.appendData(contentTypeString.dataUsingEncoding(NSUTF8StringEncoding)!)
requestBodyData.appendData(data)
requestBodyData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
requestBodyData.appendData(boundaryEnd.dataUsingEncoding(NSUTF8StringEncoding)!)
let contentDispositionString = "Content-Disposition: form-data; name=\"file\"; filename=\"\(parameters["filename"])\"\r\n"
let contentTypeString = "Content-Type: \(parameters["filetype"])\r\n\r\n"
var requestBodyData: Data = Data()
requestBodyData.append(boundaryStart.data(using: String.Encoding.utf8)!)
requestBodyData.append(contentDispositionString.data(using: String.Encoding.utf8)!)
requestBodyData.append(contentTypeString.data(using: String.Encoding.utf8)!)
requestBodyData.append(data)
requestBodyData.append("\r\n".data(using: String.Encoding.utf8)!)
requestBodyData.append(boundaryEnd.data(using: String.Encoding.utf8)!)
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
request.HTTPBody = requestBodyData
NSURLSession.sharedSession().dataTaskWithRequest(request) {
(data, response, internalError) -> Void in
self.handleResponse(data, response: response, internalError: internalError, successClosure: {(json) in
successClosure(json)
}, errorClosure: {(error) in
errorClosure(error)
})
request.httpBody = requestBodyData as Data
URLSession.shared.dataTask(with: request) {(data, response, internalError) in
do {
successClosure(try self.handleResponse(data, response: response, internalError: internalError))
} catch let error {
errorClosure(error as? SlackError ?? SlackError.unknownError)
}
}.resume()
}
private func handleResponse(data: NSData?, response:NSURLResponse?, internalError:NSError?, successClosure: ([String: AnyObject])->Void, errorClosure: (SlackError)->Void) {
guard let data = data, response = response as? NSHTTPURLResponse else {
errorClosure(SlackError.ClientNetworkError)
return
private func handleResponse(_ data: Data?, response:URLResponse?, internalError:Error?) throws -> [String: Any] {
guard let data = data, let response = response as? HTTPURLResponse else {
throw SlackError.clientNetworkError
}
do {
guard let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject] else {
errorClosure(SlackError.ClientJSONError)
return
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
throw SlackError.clientJSONError
}
switch response.statusCode {
case 200:
if (json["ok"] as! Bool == true) {
successClosure(json)
return json
} else {
if let errorString = json["error"] as? String {
throw SlackError(rawValue: errorString) ?? .UnknownError
throw SlackError(rawValue: errorString) ?? .unknownError
} else {
throw SlackError.UnknownError
throw SlackError.unknownError
}
}
case 429:
throw SlackError.TooManyRequests
throw SlackError.tooManyRequests
default:
throw SlackError.ClientNetworkError
throw SlackError.clientNetworkError
}
} catch let error {
if let slackError = error as? SlackError {
errorClosure(slackError)
throw slackError
} else {
errorClosure(SlackError.UnknownError)
throw SlackError.unknownError
}
}
}
@@ -150,4 +143,14 @@ internal struct NetworkInterface {
return String(format: "slackkit.boundary.%08x%08x", arc4random(), arc4random())
}
//MARK: - Filter Nil Parameters
private func filterNilParameters(_ parameters: [String: Any?]) -> [String: Any] {
var finalParameters = [String: Any]()
for (key, value) in parameters {
if let unwrapped = value {
finalParameters[key] = unwrapped
}
}
return finalParameters
}
}
+4 -4
View File
@@ -31,14 +31,14 @@ internal struct OAuthResponse {
let incomingWebhook: IncomingWebhook?
let bot: Bot?
init(response: [String: AnyObject]?) {
init(response: [String: Any]?) {
accessToken = response?["access_token"] as? String
scope = (response?["scope"] as? String)?.componentsSeparatedByString(",").flatMap{Scope(rawValue:$0)}
scope = (response?["scope"] as? String)?.components(separatedBy: ",").flatMap{Scope(rawValue:$0)}
userID = response?["user_id"] as? String
teamName = response?["team_name"] as? String
teamID = response?["team_id"] as? String
incomingWebhook = IncomingWebhook(webhook: response?["incoming_webhook"] as? [String: AnyObject])
bot = Bot(botUser: response?["bot"] as? [String: AnyObject])
incomingWebhook = IncomingWebhook(webhook: response?["incoming_webhook"] as? [String: Any])
bot = Bot(botUser: response?["bot"] as? [String: Any])
}
}
+19 -24
View File
@@ -25,13 +25,13 @@ import Foundation
import Swifter
internal protocol OAuthDelegate {
mutating func userAuthed(response: OAuthResponse)
func userAuthed(_ response: OAuthResponse)
}
public struct OAuthServer {
private let oauthURL = "https://slack.com/oauth/authorize"
private let http = HttpServer()
private let clientID: String
private let clientSecret: String
@@ -49,7 +49,7 @@ public struct OAuthServer {
start(port, forceIPV4: forceIPV4)
}
public func start(port: in_port_t = 8080, forceIPV4: Bool = false) {
public func start(_ port: in_port_t = 8080, forceIPV4: Bool = false) {
do {
try http.start(port, forceIPv4: forceIPV4)
} catch let error as NSError {
@@ -61,39 +61,34 @@ public struct OAuthServer {
http.stop()
}
private mutating func oauthRoute() {
private func oauthRoute() {
http["/oauth"] = { request in
guard let response = AuthorizeResponse(queryParameters: request.queryParams) where response.state == self.state else {
return .BadRequest(.Text("Bad request."))
guard let response = AuthorizeResponse(queryParameters: request.queryParams), response.state == self.state else {
return .badRequest(.text("Bad request."))
}
self.oauthRequest(response)
WebAPI.oauthAccess(clientID: self.clientID, clientSecret: self.clientSecret, code: response.code, redirectURI: self.redirectURI, success: {(response) in
self.delegate?.userAuthed(OAuthResponse(response: response))
}, failure: {(error) in
print("Authorization failed")
})
if let redirect = self.redirectURI {
return .MovedPermanently(redirect)
return .movedPermanently(redirect)
}
return .OK(.Text("Authentication successful."))
return .ok(.text("Authentication successful."))
}
}
private mutating func oauthRequest(auth: AuthorizeResponse) {
WebAPI.oauthAccess(self.clientID, clientSecret: self.clientSecret, code: auth.code, redirectURI: self.redirectURI, success: {(response) in
self.delegate?.userAuthed(OAuthResponse(response: response))
}, failure: {(error) in
})
}
private func oauthURLRequest(authorize: AuthorizeRequest) -> NSURLRequest? {
var requestString = "\(oauthURL)?client_id=\(authorize.clientID)"
requestString += authorize.parameters.requestStringFromParameters
guard let url = NSURL(string: requestString) else {
private func oauthURLRequest(_ authorize: AuthorizeRequest) -> URLRequest? {
var components = URLComponents(string: "\(oauthURL)")
components?.queryItems = [URLQueryItem(name: "client_id", value: "\(authorize.clientID)")]
guard let url = components?.url else {
return nil
}
return NSURLRequest(URL:url)
return URLRequest(url: url)
}
public func authorizeRequest(scope:[Scope], redirectURI: String, state: String = "slackkit", team: String? = nil) -> NSURLRequest? {
public func authorizeRequest(_ scope:[Scope], redirectURI: String, state: String = "slackkit", team: String? = nil) -> URLRequest? {
let request = AuthorizeRequest(clientID: clientID, scope: scope, redirectURI: redirectURI, state: state, team: team)
return oauthURLRequest(request)
}
}
+8 -10
View File
@@ -21,11 +21,12 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public struct Reaction {
public struct Reaction: Equatable {
public let name: String?
internal(set) public var user: String?
internal init(reaction:[String: AnyObject]?) {
internal init(reaction:[String: Any]?) {
name = reaction?["name"] as? String
}
@@ -34,11 +35,11 @@ public struct Reaction {
self.user = user
}
static func reactionsFromArray(array: [[String: AnyObject]]?) -> [Reaction] {
static func reactionsFromArray(_ array: [[String: Any]]?) -> [Reaction] {
var reactions = [Reaction]()
if let array = array {
for reaction in array {
if let users = reaction["users"] as? [String], name = reaction["name"] as? String {
if let users = reaction["users"] as? [String], let name = reaction["name"] as? String {
for user in users {
reactions.append(Reaction(name: name, user: user))
}
@@ -48,10 +49,7 @@ public struct Reaction {
return reactions
}
}
extension Reaction: Equatable {}
public func ==(lhs: Reaction, rhs: Reaction) -> Bool {
return lhs.name == rhs.name
public static func ==(lhs: Reaction, rhs: Reaction) -> Bool {
return lhs.name == rhs.name
}
}
+3 -4
View File
@@ -33,12 +33,11 @@ public struct Response {
self.attachments = attachments
}
internal func json() -> [String: AnyObject] {
var json = [String : AnyObject]()
internal var json: [String: Any] {
var json = [String : Any]()
json["text"] = text
json["response_type"] = responseType?.rawValue
json["attachments"] = attachments?.map({$0.dictionary()})
json["attachments"] = attachments?.map({$0.dictionary})
return json
}
}
+23 -24
View File
@@ -25,16 +25,16 @@ import Foundation
import Swifter
internal enum Reply {
case JSON(response: Response)
case Text(body: String)
case BadRequest
case json(response: Response)
case text(body: String)
case badRequest
}
internal protocol Request {
var responseURL: String { get }
}
public class Server {
open class Server {
internal let http = HttpServer()
internal let token: String
@@ -43,7 +43,7 @@ public class Server {
self.token = token
}
public func start(port: in_port_t = 8080, forceIPV4: Bool = false) {
open func start(_ port: in_port_t = 8080, forceIPV4: Bool = false) {
do {
try http.start(port, forceIPv4: forceIPV4)
} catch let error as NSError {
@@ -51,29 +51,29 @@ public class Server {
}
}
public func stop() {
open func stop() {
http.stop()
}
internal func request(request:Request, reply: Reply) -> HttpResponse {
internal func request(_ request:Request, reply: Reply) -> HttpResponse {
switch reply {
case .Text(let body):
return .OK(.Text(body))
case .JSON(let response):
return .OK(.Json(response.json()))
case .BadRequest:
return .BadRequest(.Text("Bad request."))
case .text(let body):
return .ok(.text(body))
case .json(let response):
return .ok(.json(response.json as AnyObject))
case .badRequest:
return .badRequest(.text("Bad request."))
}
}
internal func dictionaryFromRequest(body: [UInt8]) -> [String: AnyObject]? {
let string = NSString(data: NSData(bytes: body, length: body.count), encoding: NSUTF8StringEncoding)
if let body = string?.componentsSeparatedByString("&") {
var dict: [String: AnyObject] = [:]
internal func dictionaryFromRequest(_ body: [UInt8]) -> [String: Any]? {
let string = String(data: Data(bytes: UnsafePointer<UInt8>(body), count: body.count), encoding: String.Encoding.utf8)
if let body = string?.components(separatedBy: "&") {
var dict: [String: Any] = [:]
for argument in body {
let kv = argument.componentsSeparatedByString("=")
if let key = kv.first, value = kv.last {
dict[key] = value
let kv = argument.components(separatedBy: "=")
if let key = kv.first, let value = kv.last {
dict[key] = value as Any?
}
}
return dict
@@ -81,11 +81,10 @@ public class Server {
return nil
}
internal func jsonFromRequest(string: String) -> [String: AnyObject]? {
guard let data = string.dataUsingEncoding(NSUTF8StringEncoding) else {
internal func jsonFromRequest(_ string: String) -> [String: Any]? {
guard let data = string.data(using: String.Encoding.utf8) else {
return nil
}
return (try? NSJSONSerialization.JSONObjectWithData(data, options: [])) as? [String: AnyObject] ?? nil
return (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] ?? nil
}
}
+95 -94
View File
@@ -21,100 +21,101 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public enum SlackError: String, ErrorType {
case AccountInactive = "account_inactive"
case AlreadyArchived = "already_archived"
case AlreadyInChannel = "already_in_channel"
case AlreadyPinned = "already_pinned"
case AlreadyReacted = "already_reacted"
case AlreadyStarred = "already_starred"
case BadClientSecret = "bad_client_secret"
case BadRedirectURI = "bad_redirect_uri"
case BadTimeStamp = "bad_timestamp"
case CantArchiveGeneral = "cant_archive_general"
case CantDelete = "cant_delete"
case CantDeleteFile = "cant_delete_file"
case CantDeleteMessage = "cant_delete_message"
case CantInvite = "cant_invite"
case CantInviteSelf = "cant_invite_self"
case CantKickFromGeneral = "cant_kick_from_general"
case CantKickFromLastChannel = "cant_kick_from_last_channel"
case CantKickSelf = "cant_kick_self"
case CantLeaveGeneral = "cant_leave_general"
case CantLeaveLastChannel = "cant_leave_last_channel"
case CantUpdateMessage = "cant_update_message"
case ChannelNotFound = "channel_not_found"
case ComplianceExportsPreventDeletion = "compliance_exports_prevent_deletion"
case EditWindowClosed = "edit_window_closed"
case FileCommentNotFound = "file_comment_not_found"
case FileDeleted = "file_deleted"
case FileNotFound = "file_not_found"
case FileNotShared = "file_not_shared"
case GroupContainsOthers = "group_contains_others"
case InvalidArgName = "invalid_arg_name"
case InvalidArrayArg = "invalid_array_arg"
case InvalidAuth = "invalid_auth"
case InvalidChannel = "invalid_channel"
case InvalidCharSet = "invalid_charset"
case InvalidClientID = "invalid_client_id"
case InvalidCode = "invalid_code"
case InvalidFormData = "invalid_form_data"
case InvalidName = "invalid_name"
case InvalidPostType = "invalid_post_type"
case InvalidPresence = "invalid_presence"
case InvalidTS = "invalid_timestamp"
case InvalidTSLatest = "invalid_ts_latest"
case InvalidTSOldest = "invalid_ts_oldest"
case IsArchived = "is_archived"
case LastMember = "last_member"
case LastRAChannel = "last_ra_channel"
case MessageNotFound = "message_not_found"
case MessageTooLong = "msg_too_long"
case MigrationInProgress = "migration_in_progress"
case MissingDuration = "missing_duration"
case MissingPostType = "missing_post_type"
case NameTaken = "name_taken"
case NoChannel = "no_channel"
case NoComment = "no_comment"
case NoItemSpecified = "no_item_specified"
case NoReaction = "no_reaction"
case NoText = "no_text"
case NotArchived = "not_archived"
case NotAuthed = "not_authed"
case NotEnoughUsers = "not_enough_users"
case NotInChannel = "not_in_channel"
case NotInGroup = "not_in_group"
case NotPinned = "not_pinned"
case NotStarred = "not_starred"
case OverPaginationLimit = "over_pagination_limit"
case PaidOnly = "paid_only"
case PermissionDenied = "perimssion_denied"
case PostingToGeneralChannelDenied = "posting_to_general_channel_denied"
case RateLimited = "rate_limited"
case RequestTimeout = "request_timeout"
case RestrictedAction = "restricted_action"
case SnoozeEndFailed = "snooze_end_failed"
case SnoozeFailed = "snooze_failed"
case SnoozeNotActive = "snooze_not_active"
case TooLong = "too_long"
case TooManyEmoji = "too_many_emoji"
case TooManyReactions = "too_many_reactions"
case TooManyUsers = "too_many_users"
case UnknownError
case UnknownType = "unknown_type"
case UserDisabled = "user_disabled"
case UserDoesNotOwnChannel = "user_does_not_own_channel"
case UserIsBot = "user_is_bot"
case UserIsRestricted = "user_is_restricted"
case UserIsUltraRestricted = "user_is_ultra_restricted"
case UserListNotSupplied = "user_list_not_supplied"
case UserNotFound = "user_not_found"
case UserNotVisible = "user_not_visible"
public enum SlackError: String, Error {
case accountInactive = "account_inactive"
case alreadyArchived = "already_archived"
case alreadyInChannel = "already_in_channel"
case alreadyPinned = "already_pinned"
case alreadyReacted = "already_reacted"
case alreadyStarred = "already_starred"
case badClientSecret = "bad_client_secret"
case badRedirectURI = "bad_redirect_uri"
case badTimeStamp = "bad_timestamp"
case cantArchiveGeneral = "cant_archive_general"
case cantDelete = "cant_delete"
case cantDeleteFile = "cant_delete_file"
case cantDeleteMessage = "cant_delete_message"
case cantInvite = "cant_invite"
case cantInviteSelf = "cant_invite_self"
case cantKickFromGeneral = "cant_kick_from_general"
case cantKickFromLastChannel = "cant_kick_from_last_channel"
case cantKickSelf = "cant_kick_self"
case cantLeaveGeneral = "cant_leave_general"
case cantLeaveLastChannel = "cant_leave_last_channel"
case cantUpdateMessage = "cant_update_message"
case channelNotFound = "channel_not_found"
case complianceExportsPreventDeletion = "compliance_exports_prevent_deletion"
case editWindowClosed = "edit_window_closed"
case fileCommentNotFound = "file_comment_not_found"
case fileDeleted = "file_deleted"
case fileNotFound = "file_not_found"
case fileNotShared = "file_not_shared"
case groupContainsOthers = "group_contains_others"
case invalidArgName = "invalid_arg_name"
case invalidArrayArg = "invalid_array_arg"
case invalidAuth = "invalid_auth"
case invalidChannel = "invalid_channel"
case invalidCharSet = "invalid_charset"
case invalidClientID = "invalid_client_id"
case invalidCode = "invalid_code"
case invalidFormData = "invalid_form_data"
case invalidName = "invalid_name"
case invalidPostType = "invalid_post_type"
case invalidPresence = "invalid_presence"
case invalidTS = "invalid_timestamp"
case invalidTSLatest = "invalid_ts_latest"
case invalidTSOldest = "invalid_ts_oldest"
case isArchived = "is_archived"
case lastMember = "last_member"
case lastRAChannel = "last_ra_channel"
case messageNotFound = "message_not_found"
case messageTooLong = "msg_too_long"
case migrationInProgress = "migration_in_progress"
case missingDuration = "missing_duration"
case missingPostType = "missing_post_type"
case missingScope = "missing_scope"
case nameTaken = "name_taken"
case noChannel = "no_channel"
case noComment = "no_comment"
case noItemSpecified = "no_item_specified"
case noReaction = "no_reaction"
case noText = "no_text"
case notArchived = "not_archived"
case notAuthed = "not_authed"
case notEnoughUsers = "not_enough_users"
case notInChannel = "not_in_channel"
case notInGroup = "not_in_group"
case notPinned = "not_pinned"
case notStarred = "not_starred"
case overPaginationLimit = "over_pagination_limit"
case paidOnly = "paid_only"
case permissionDenied = "perimssion_denied"
case postingToGeneralChannelDenied = "posting_to_general_channel_denied"
case rateLimited = "rate_limited"
case requestTimeout = "request_timeout"
case restrictedAction = "restricted_action"
case snoozeEndFailed = "snooze_end_failed"
case snoozeFailed = "snooze_failed"
case snoozeNotActive = "snooze_not_active"
case tooLong = "too_long"
case tooManyEmoji = "too_many_emoji"
case tooManyReactions = "too_many_reactions"
case tooManyUsers = "too_many_users"
case unknownError
case unknownType = "unknown_type"
case userDisabled = "user_disabled"
case userDoesNotOwnChannel = "user_does_not_own_channel"
case userIsBot = "user_is_bot"
case userIsRestricted = "user_is_restricted"
case userIsUltraRestricted = "user_is_ultra_restricted"
case userListNotSupplied = "user_list_not_supplied"
case userNotFound = "user_not_found"
case userNotVisible = "user_not_visible"
// Client
case ClientNetworkError
case ClientJSONError
case ClientOAuthError
case clientNetworkError
case clientJSONError
case clientOAuthError
// HTTP
case TooManyRequests
case UnknownHTTPError
case tooManyRequests
case unknownHTTPError
}
+2 -3
View File
@@ -35,7 +35,7 @@ public final class SlackKit: OAuthDelegate {
public init(withAPIToken token: String, clientOptions: ClientOptions = ClientOptions()) {
self.clientOptions = clientOptions
let client = Client(apiToken: token)
dispatch_async(dispatch_get_main_queue(), {
DispatchQueue.main.async(execute: {
self.onClientInitalization?(client)
})
clients[token] = client
@@ -48,7 +48,7 @@ public final class SlackKit: OAuthDelegate {
oauth = try? OAuthServer(clientID: clientID, clientSecret: clientSecret, state: state, redirectURI: redirectURI, port: port, forceIPV4: forceIPV4, delegate: self)
}
internal func userAuthed(response: OAuthResponse) {
internal func userAuthed(_ response: OAuthResponse) {
// User auth
if let token = response.accessToken {
let client = Client(apiToken: token)
@@ -63,5 +63,4 @@ public final class SlackKit: OAuthDelegate {
client.connect(options: self.clientOptions)
}
}
}
+4 -4
View File
@@ -29,19 +29,19 @@ public struct Team {
internal(set) public var emailDomain: String?
internal(set) public var messageEditWindowMinutes: Int?
internal(set) public var overStorageLimit: Bool?
internal(set) public var prefs: [String: AnyObject]?
internal(set) public var prefs: [String: Any]?
internal(set) public var plan: String?
internal(set) public var icon: TeamIcon?
internal init(team: [String: AnyObject]?) {
internal init(team: [String: Any]?) {
id = team?["id"] as? String
name = team?["name"] as? String
domain = team?["domain"] as? String
emailDomain = team?["email_domain"] as? String
messageEditWindowMinutes = team?["msg_edit_window_mins"] as? Int
overStorageLimit = team?["over_storage_limit"] as? Bool
prefs = team?["prefs"] as? [String: AnyObject]
prefs = team?["prefs"] as? [String: Any]
plan = team?["plan"] as? String
icon = TeamIcon(icon: team?["icon"] as? [String: AnyObject])
icon = TeamIcon(icon: team?["icon"] as? [String: Any])
}
}
+2 -1
View File
@@ -22,6 +22,7 @@
// THE SOFTWARE.
public struct TeamIcon {
internal(set) public var image34: String?
internal(set) public var image44: String?
internal(set) public var image68: String?
@@ -31,7 +32,7 @@ public struct TeamIcon {
internal(set) public var imageOriginal: String?
internal(set) public var imageDefault: Bool?
internal init(icon: [String: AnyObject]?) {
internal init(icon: [String: Any]?) {
image34 = icon?["image_34"] as? String
image44 = icon?["image_44"] as? String
image68 = icon?["image_68"] as? String
+2 -1
View File
@@ -22,11 +22,12 @@
// THE SOFTWARE.
public struct Topic {
public let value: String?
public let creator: String?
public let lastSet: Int?
internal init(topic: [String: AnyObject]?) {
internal init(topic: [String: Any]?) {
value = topic?["value"] as? String
creator = topic?["creator"] as? String
lastSet = topic?["last_set"] as? Int
+8 -8
View File
@@ -24,6 +24,7 @@
public struct User {
public struct Profile {
internal(set) public var firstName: String?
internal(set) public var lastName: String?
internal(set) public var realName: String?
@@ -37,7 +38,7 @@ public struct User {
internal(set) public var image192: String?
internal(set) public var customProfile: CustomProfile?
internal init(profile: [String: AnyObject]?) {
internal init(profile: [String: Any]?) {
firstName = profile?["first_name"] as? String
lastName = profile?["last_name"] as? String
realName = profile?["real_name"] as? String
@@ -49,11 +50,10 @@ public struct User {
image48 = profile?["image_48"] as? String
image72 = profile?["image_72"] as? String
image192 = profile?["image_192"] as? String
customProfile = CustomProfile(customFields: profile?["fields"] as? [String: AnyObject])
customProfile = CustomProfile(customFields: profile?["fields"] as? [String: Any])
}
}
public let id: String?
internal(set) public var name: String?
internal(set) public var deleted: Bool?
@@ -73,15 +73,15 @@ public struct User {
internal(set) public var timeZone: String?
internal(set) public var timeZoneLabel: String?
internal(set) public var timeZoneOffSet: Int?
internal(set) public var preferences: [String: AnyObject]?
internal(set) public var preferences: [String: Any]?
// Client properties
internal(set) public var userGroups: [String: String]?
internal init(user: [String: AnyObject]?) {
internal init(user: [String: Any]?) {
id = user?["id"] as? String
name = user?["name"] as? String
deleted = user?["deleted"] as? Bool
profile = Profile(profile: user?["profile"] as? [String: AnyObject])
profile = Profile(profile: user?["profile"] as? [String: Any])
color = user?["color"] as? String
isAdmin = user?["is_admin"] as? Bool
isOwner = user?["is_owner"] as? Bool
@@ -96,11 +96,11 @@ public struct User {
timeZone = user?["tz"] as? String
timeZoneLabel = user?["tz_label"] as? String
timeZoneOffSet = user?["tz_offset"] as? Int
preferences = user?["prefs"] as? [String: AnyObject]
preferences = user?["prefs"] as? [String: Any]
}
internal init(id: String?) {
self.id = id
self.isBot = nil
}
}
}
+3 -4
View File
@@ -37,11 +37,11 @@ public struct UserGroup {
public let createdBy: String?
internal(set) public var updatedBy: String?
internal(set) public var deletedBy: String?
internal(set) public var preferences: [String: AnyObject]?
internal(set) public var preferences: [String: Any]?
internal(set) public var users: [String]?
internal(set) public var userCount: Int?
internal init(userGroup: [String: AnyObject]?) {
internal init(userGroup: [String: Any]?) {
id = userGroup?["id"] as? String
teamID = userGroup?["team_id"] as? String
isUserGroup = userGroup?["is_usergroup"] as? Bool
@@ -56,11 +56,10 @@ public struct UserGroup {
createdBy = userGroup?["created_by"] as? String
updatedBy = userGroup?["updated_by"] as? String
deletedBy = userGroup?["deleted_by"] as? String
preferences = userGroup?["prefs"] as? [String: AnyObject]
preferences = userGroup?["prefs"] as? [String: Any]
users = userGroup?["users"] as? [String]
if let count = userGroup?["user_count"] as? String {
userCount = Int(count)
}
}
}
File diff suppressed because it is too large Load Diff
+1 -2
View File
@@ -34,7 +34,7 @@ internal struct WebhookRequest: Request {
let text: String
let responseURL: String
init(request: [String: AnyObject]?) {
init(request: [String: Any]?) {
token = request?["token"] as? String
teamID = request?["team_id"] as? String ?? ""
teamDomain = request?["team_domain"] as? String ?? ""
@@ -46,5 +46,4 @@ internal struct WebhookRequest: Request {
text = request?["text"] as? String ?? ""
responseURL = request?["response_url"] as? String ?? ""
}
}
+6 -7
View File
@@ -21,30 +21,29 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public class WebhookServer: Server {
open class WebhookServer: Server {
public init(token: String, route: String, response: Response) {
super.init(token: token)
addRoute(route, response: response)
}
public func addRoute(route: String, response: Response) {
open func addRoute(_ route: String, response: Response) {
http["/\(route)"] = { request in
let webhookRequest = WebhookRequest(request: self.dictionaryFromRequest(request.body))
if webhookRequest.token == self.token {
return self.request(webhookRequest, reply: self.replyForResponse(response))
} else {
return .BadRequest(.Text("Bad request."))
return .badRequest(.text("Bad request."))
}
}
}
private func replyForResponse(response: Response) -> Reply {
private func replyForResponse(_ response: Response) -> Reply {
if response.attachments == nil && response.responseType == nil {
return Reply.Text(body: response.text)
return Reply.text(body: response.text)
} else {
return Reply.JSON(response: response)
return Reply.json(response: response)
}
}
}
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.0.0</string>
<string>3.1.7</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.0.0</string>
<string>3.1.7</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.0.0</string>
<string>3.1.7</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>