Compare commits

..

56 Commits

Author SHA1 Message Date
Peter Zignego 00b2605a37 Add public contains extension 2016-05-05 13:14:48 -04:00
Peter Zignego 2561e8ba48 Bug fix 2016-05-04 23:31:02 -04:00
Peter Zignego 00b0823dbd Percent encoding bug fix 2016-05-04 23:25:19 -04:00
Peter Zignego b88ef3638c Project file updates 2016-05-04 20:37:09 -04:00
Peter Zignego 1675aa82fb Use foundation for percent encoding for now 2016-05-04 15:04:25 -04:00
Peter Zignego 01be45e979 Fixes 2016-05-03 19:15:37 -04:00
Peter Zignego dc3336a807 Percent encoding fix 2016-05-03 00:41:28 -04:00
Peter Zignego 5962ce5115 Fixes 2016-05-02 21:22:47 -04:00
Peter Zignego db6bf52eaa Update dependencies 2016-05-02 17:57:06 -04:00
Peter Zignego 32ae1ed7a2 Remove foundation dependencies 2016-05-02 17:56:35 -04:00
Peter Zignego 2e4b4390b3 Zewo implementation 2016-05-02 13:40:53 -04:00
Peter Zignego 07861887f1 Start Zewo implementation 2016-05-02 11:19:27 -04:00
Peter Zignego 1c9b7bb011 Remove example 2016-05-02 11:19:13 -04:00
Peter Zignego 59e1e8856d Swift 3 renaming 2016-05-02 10:36:11 -04:00
Peter Zignego 76b33dba0e Setup 2016-05-02 10:35:56 -04:00
Peter Zignego 6040d8deaa Clean up 2016-05-02 10:35:38 -04:00
Peter Zignego b2be8d0170 Merge pull request #24 from pvzig/1.0.1
v1.0.1
2016-04-09 11:40:17 -04:00
Peter Zignego 45be1b7a3f Bump version number 2016-04-09 11:33:22 -04:00
Peter Zignego 09aa72d43e Update readme to include explanation of Leaderboard example 2016-04-09 11:24:47 -04:00
Peter Zignego bf4b55bbd6 Add leaderboard bot example 2016-04-09 11:02:30 -04:00
Peter Zignego a82279fad1 Code cleanup and improvement 2016-04-04 23:49:25 -04:00
Peter Zignego 500e489d5d Add AttachmentField type and AttachmentColor enum 2016-04-04 21:26:09 -04:00
Peter Zignego 874f4f51e1 Fix send message optional parameter handling 2016-04-03 21:04:49 -04:00
Peter Zignego 654f419f4e Support for rtm.start parameters 2016-04-03 15:45:53 -04:00
Peter Zignego a7c25fe33b Version bump 2016-03-22 21:55:26 -04:00
Peter Zignego d2037f4cc5 Merge pull request #23 from pvzig/feature/client-improvements
Feature/client-improvements
2016-03-22 21:44:20 -04:00
Peter Zignego b87232dfb5 Readme updates 2016-03-22 21:38:17 -04:00
Peter Zignego 9e5678739f Update readme 2016-03-22 21:34:45 -04:00
Peter Zignego 5cc8582d65 Code cleanup 2016-03-22 21:29:16 -04:00
Peter Zignego aa078934c0 File comment web api errors 2016-03-22 20:56:10 -04:00
Peter Zignego 5c157caea3 Client improvements - disconnect, ping-pong, timeout, reconnect 2016-03-22 20:50:29 -04:00
Peter Zignego b567113b5f Update Starscream dependency version 2016-03-22 20:44:58 -04:00
Peter Zignego 5b08fb6031 Merge pull request #21 from pvzig/feature/file-comment
Add support for file comment web API calls
2016-03-19 14:21:52 -04:00
Peter Zignego b48f33fb72 Add support for file comment web API calls 2016-03-19 14:12:04 -04:00
Peter Zignego deccb727a1 Merge pull request #20 from pvzig/feature/reactions-itemUser
Add support for the item user reaction property
2016-03-15 23:48:55 -04:00
Peter Zignego 8f1df8d138 Add support for the itemUser reaction property 2016-03-15 23:48:08 -04:00
Peter Zignego 0048710e24 Merge pull request #19 from pvzig/feature/dnd-read
DND Read Scope Web API implementation
2016-03-15 23:38:08 -04:00
Peter Zignego f6da0ddd32 DND read scope fixes 2016-03-15 23:37:33 -04:00
Peter Zignego 513485e704 DND Read Scope Web API implementation 2016-03-15 23:28:38 -04:00
Peter Zignego fb3719c29d Merge pull request #18 from pvzig/feature/rtm-team-profile
Add support for team profile events
2016-03-15 22:48:43 -04:00
Peter Zignego 76fdc55f9e Team profile events 2016-03-15 22:45:45 -04:00
Peter Zignego 687b57fc1f Version bump 2016-03-01 23:08:24 -05:00
Peter Zignego 319dc9a095 Merge pull request #17 from muratayusuke/bugfix/ignore_int_param
Bugfix: Do not ignore Int and Bool parameters when making requests to the web api
2016-03-01 12:47:20 -05:00
muratayusuke 64440b5c5b Do not ignore Int/Bool param such as count 2016-03-02 02:25:37 +09:00
Peter Zignego 3efe5752cb Merge pull request #16 from pvzig/feature/history-object
Feature/history object
2016-02-28 12:41:22 -05:00
Peter Zignego 31f69e3afd Move History struct to Types.swift, minor changes 2016-02-28 12:40:04 -05:00
muratayusuke 72b29562e5 Introduce history type 2016-02-28 12:29:12 -05:00
Peter Zignego 2b26eb35d7 Merge pull request #14 from pvzig/fix/team-object
fix/team-object
2016-02-27 14:13:53 -05:00
Peter Zignego c4c8e99c0b Bug fixes, team icon support 2016-02-27 14:10:35 -05:00
muratayusuke 5efe222196 Add team icon 2016-02-27 14:06:24 -05:00
Peter Zignego e56ff971b2 Merge pull request #12 from hamin/public-message-initializer
Making Message struct initializer public.
2016-02-27 13:48:42 -05:00
Haris Amin 18b8a31d85 Making Message struct initializer public. 2016-02-27 13:38:52 -05:00
Peter Zignego d386730c75 Project file update 2016-02-21 10:31:13 -05:00
Peter Zignego bc6e94d99a Merge pull request #11 from pvzig/feature/message-attachments
Message attachment support
2016-02-21 10:27:41 -05:00
Peter Zignego 89f5e3786e Message attachment support 2016-02-21 10:18:32 -05:00
Peter Zignego 0665ea0270 Add sample app 2016-02-18 18:21:17 -05:00
29 changed files with 5551 additions and 850 deletions
+4 -3
View File
@@ -27,7 +27,8 @@ let package = Package(
name: "SlackKit",
targets: [],
dependencies: [
.Package(url: "https://github.com/pvzig/Starscream.git",
majorVersion: 1),
]
.Package(url: "https://github.com/open-swift/C7.git", majorVersion: 0, minor: 5),
.Package(url: "https://github.com/czechboy0/Jay.git", majorVersion: 0, minor: 5),
.Package(url: "https://github.com/Zewo/WebSocket", majorVersion: 0, minor: 5),
]
)
-7
View File
@@ -1,7 +0,0 @@
source 'https://github.com/CocoaPods/Specs.git'
use_frameworks!
target 'SlackKit' do
pod 'Starscream'
end
-10
View File
@@ -1,10 +0,0 @@
PODS:
- Starscream (1.0.2)
DEPENDENCIES:
- Starscream
SPEC CHECKSUMS:
Starscream: 40e2c4c1c770d811f24116b8b7dbeb4542c56767
COCOAPODS: 0.39.0
+23 -4
View File
@@ -12,7 +12,7 @@ import PackageDescription
let package = Package(
dependencies: [
.Package(url: "https://github.com/pvzig/SlackKit.git", majorVersion: 0)
.Package(url: "https://github.com/pvzig/SlackKit.git", majorVersion: 1)
]
)
```
@@ -40,7 +40,6 @@ To use SlackKit you'll need a bearer token which identifies a single user. You c
Once you have a token, initialize a client instance using it:
```swift
let client = Client(apiToken: "YOUR_SLACK_API_TOKEN")
```
If you want to receive messages from the Slack RTM API, connect to it.
@@ -48,6 +47,11 @@ If you want to receive messages from the Slack RTM API, connect to it.
client.connect()
```
You can also set options for a ping/pong interval, timeout interval, and automatic reconnection:
```swift
client.connect(pingInterval: 2, timeout: 10, reconnect: false)
```
Once connected, the client will begin to consume any messages sent by the Slack RTM API.
####Web API Methods
@@ -65,6 +69,9 @@ SlackKit currently supports the a subset of the Slack Web APIs that are availabl
- chat.postMessage
- chat.update
- emoji.list
- files.comments.add
- files.comments.edit
- files.comments.delete
- files.delete
- files.upload
- groups.close
@@ -187,8 +194,8 @@ func itemStarred(item: Item, star: Bool)
#####ReactionEventsDelegate
```swift
func reactionAdded(reaction: String?, item: Item?)
func reactionRemoved(reaction: String?, item: Item?)
func reactionAdded(reaction: String?, item: Item?, itemUser: String?)
func reactionRemoved(reaction: String?, item: Item?, itemUser: String?)
```
#####TeamEventsDelegate
@@ -209,6 +216,18 @@ func subteamSelfAdded(subteamID: String)
func subteamSelfRemoved(subteamID: String)
```
###Examples
####Leaderboard
Included in the OSX-Sample is an example application of a bot you might make using SlackKit. Its a basic leaderboard scoring bot, in the spirit of [PlusPlus](https://plusplus.chat).
To configure it, enter your bots API token in `AppDelegate.swift` for the Leaderboard bot:
```swift
let learderboard = Leaderboard(token: "SLACK_AUTH_TOKEN")
```
It adds a point for every `@thing++`, subtracts a point for every `@thing--`, and shows a leaderboard when asked `@botname leaderboard`.
###Get In Touch
[@pvzig](https://twitter.com/pvzig)
-16
View File
@@ -1,16 +0,0 @@
Pod::Spec.new do |s|
s.name = "SlackKit"
s.version = "0.9.8"
s.summary = "a Slack client library for iOS and OS X written in Swift"
s.homepage = "https://github.com/pvzig/SlackKit"
s.license = 'MIT'
s.author = { "Peter Zignego" => "peter@launchsoft.co" }
s.source = { :git => "https://github.com/pvzig/SlackKit.git", :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/pvzig'
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.9'
s.requires_arc = true
s.source_files = 'SlackKit/Sources/*.swift'
s.frameworks = 'Foundation'
s.dependency 'Starscream', '~> 1.0.2'
end
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,72 @@
{
"DVTSourceControlWorkspaceBlueprintPrimaryRemoteRepositoryKey" : "7C8CB4917A87F5E5383E6800524CC50437576509",
"DVTSourceControlWorkspaceBlueprintWorkingCopyRepositoryLocationsKey" : {
},
"DVTSourceControlWorkspaceBlueprintWorkingCopyStatesKey" : {
"7C8CB4917A87F5E5383E6800524CC50437576509" : 0,
"15033DFF73D1DAA84A806DC9B6994613D8A2EB4F" : 0,
"4B8317071C2E8191C0071D14B19E229FF434BD5B" : 0,
"8951CEB15DDB2D711276960E67900B8AA34FF427" : 0,
"10A2CB6C4392F0E306FF8D509BE5E88232276EA4" : 0,
"269ADF55FAAC04D68303BE30B6BD693E717155DE" : 0,
"997F6D72B6636BD16A82A9AFFBB55CCAE1A5596D" : 0,
"704B817219E4CBC31AA92368EF54A4E2835A8C3D" : 0
},
"DVTSourceControlWorkspaceBlueprintIdentifierKey" : "06B58BC9-590E-416B-85DA-67AE0673C049",
"DVTSourceControlWorkspaceBlueprintWorkingCopyPathsKey" : {
"7C8CB4917A87F5E5383E6800524CC50437576509" : "SlackKit\/",
"15033DFF73D1DAA84A806DC9B6994613D8A2EB4F" : "SlackKit\/Packages\/IP-0.5.0\/",
"4B8317071C2E8191C0071D14B19E229FF434BD5B" : "SlackKit\/Packages\/WebSocket-0.5.1\/",
"8951CEB15DDB2D711276960E67900B8AA34FF427" : "SlackKit\/Packages\/MediaType-0.5.0\/",
"10A2CB6C4392F0E306FF8D509BE5E88232276EA4" : "SlackKit\/Packages\/String-0.5.1\/",
"269ADF55FAAC04D68303BE30B6BD693E717155DE" : "SlackKit\/Packages\/CHTTPParser-0.5.0\/",
"997F6D72B6636BD16A82A9AFFBB55CCAE1A5596D" : "SlackKit\/Packages\/TCPSSL-0.5.1\/",
"704B817219E4CBC31AA92368EF54A4E2835A8C3D" : "SlackKit\/Packages\/POSIX-0.5.0\/"
},
"DVTSourceControlWorkspaceBlueprintNameKey" : "SlackKit",
"DVTSourceControlWorkspaceBlueprintVersion" : 204,
"DVTSourceControlWorkspaceBlueprintRelativePathToProjectKey" : "SlackKit.xcodeproj",
"DVTSourceControlWorkspaceBlueprintRemoteRepositoriesKey" : [
{
"DVTSourceControlWorkspaceBlueprintRemoteRepositoryURLKey" : "https:\/\/github.com\/Zewo\/String.git",
"DVTSourceControlWorkspaceBlueprintRemoteRepositorySystemKey" : "com.apple.dt.Xcode.sourcecontrol.Git",
"DVTSourceControlWorkspaceBlueprintRemoteRepositoryIdentifierKey" : "10A2CB6C4392F0E306FF8D509BE5E88232276EA4"
},
{
"DVTSourceControlWorkspaceBlueprintRemoteRepositoryURLKey" : "https:\/\/github.com\/VeniceX\/IP.git",
"DVTSourceControlWorkspaceBlueprintRemoteRepositorySystemKey" : "com.apple.dt.Xcode.sourcecontrol.Git",
"DVTSourceControlWorkspaceBlueprintRemoteRepositoryIdentifierKey" : "15033DFF73D1DAA84A806DC9B6994613D8A2EB4F"
},
{
"DVTSourceControlWorkspaceBlueprintRemoteRepositoryURLKey" : "https:\/\/github.com\/Zewo\/CHTTPParser.git",
"DVTSourceControlWorkspaceBlueprintRemoteRepositorySystemKey" : "com.apple.dt.Xcode.sourcecontrol.Git",
"DVTSourceControlWorkspaceBlueprintRemoteRepositoryIdentifierKey" : "269ADF55FAAC04D68303BE30B6BD693E717155DE"
},
{
"DVTSourceControlWorkspaceBlueprintRemoteRepositoryURLKey" : "https:\/\/github.com\/Zewo\/WebSocket",
"DVTSourceControlWorkspaceBlueprintRemoteRepositorySystemKey" : "com.apple.dt.Xcode.sourcecontrol.Git",
"DVTSourceControlWorkspaceBlueprintRemoteRepositoryIdentifierKey" : "4B8317071C2E8191C0071D14B19E229FF434BD5B"
},
{
"DVTSourceControlWorkspaceBlueprintRemoteRepositoryURLKey" : "https:\/\/github.com\/Zewo\/POSIX.git",
"DVTSourceControlWorkspaceBlueprintRemoteRepositorySystemKey" : "com.apple.dt.Xcode.sourcecontrol.Git",
"DVTSourceControlWorkspaceBlueprintRemoteRepositoryIdentifierKey" : "704B817219E4CBC31AA92368EF54A4E2835A8C3D"
},
{
"DVTSourceControlWorkspaceBlueprintRemoteRepositoryURLKey" : "https:\/\/github.com\/pvzig\/SlackRTMKit.git",
"DVTSourceControlWorkspaceBlueprintRemoteRepositorySystemKey" : "com.apple.dt.Xcode.sourcecontrol.Git",
"DVTSourceControlWorkspaceBlueprintRemoteRepositoryIdentifierKey" : "7C8CB4917A87F5E5383E6800524CC50437576509"
},
{
"DVTSourceControlWorkspaceBlueprintRemoteRepositoryURLKey" : "https:\/\/github.com\/Zewo\/MediaType.git",
"DVTSourceControlWorkspaceBlueprintRemoteRepositorySystemKey" : "com.apple.dt.Xcode.sourcecontrol.Git",
"DVTSourceControlWorkspaceBlueprintRemoteRepositoryIdentifierKey" : "8951CEB15DDB2D711276960E67900B8AA34FF427"
},
{
"DVTSourceControlWorkspaceBlueprintRemoteRepositoryURLKey" : "https:\/\/github.com\/VeniceX\/TCPSSL.git",
"DVTSourceControlWorkspaceBlueprintRemoteRepositorySystemKey" : "com.apple.dt.Xcode.sourcecontrol.Git",
"DVTSourceControlWorkspaceBlueprintRemoteRepositoryIdentifierKey" : "997F6D72B6636BD16A82A9AFFBB55CCAE1A5596D"
}
]
}
@@ -0,0 +1,467 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "9999"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_C7"
BuildableName = "libC7.dylib"
BlueprintName = "C7"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_Jay"
BuildableName = "libJay.dylib"
BlueprintName = "Jay"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "NO"
buildForRunning = "NO"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_JayExample"
BuildableName = "JayExample"
BlueprintName = "JayExample"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_String"
BuildableName = "libString.dylib"
BlueprintName = "String"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_StructuredData"
BuildableName = "libStructuredData.dylib"
BlueprintName = "StructuredData"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_MediaType"
BuildableName = "libMediaType.dylib"
BlueprintName = "MediaType"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_CURIParser"
BuildableName = "libCURIParser.dylib"
BlueprintName = "CURIParser"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_URI"
BuildableName = "libURI.dylib"
BlueprintName = "URI"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_S4"
BuildableName = "libS4.dylib"
BlueprintName = "S4"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_HTTP"
BuildableName = "libHTTP.dylib"
BlueprintName = "HTTP"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_CLibvenice"
BuildableName = "libCLibvenice.dylib"
BlueprintName = "CLibvenice"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_Venice"
BuildableName = "libVenice.dylib"
BlueprintName = "Venice"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_POSIX"
BuildableName = "libPOSIX.dylib"
BlueprintName = "POSIX"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_IP"
BuildableName = "libIP.dylib"
BlueprintName = "IP"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_TCP"
BuildableName = "libTCP.dylib"
BlueprintName = "TCP"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_CHTTPParser"
BuildableName = "libCHTTPParser.dylib"
BlueprintName = "CHTTPParser"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_HTTPParser"
BuildableName = "libHTTPParser.dylib"
BlueprintName = "HTTPParser"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_HTTPSerializer"
BuildableName = "libHTTPSerializer.dylib"
BlueprintName = "HTTPSerializer"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_HTTPClient"
BuildableName = "libHTTPClient.dylib"
BlueprintName = "HTTPClient"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_File"
BuildableName = "libFile.dylib"
BlueprintName = "File"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_OpenSSL"
BuildableName = "libOpenSSL.dylib"
BlueprintName = "OpenSSL"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_TCPSSL"
BuildableName = "libTCPSSL.dylib"
BlueprintName = "TCPSSL"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_HTTPSClient"
BuildableName = "libHTTPSClient.dylib"
BlueprintName = "HTTPSClient"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_Event"
BuildableName = "libEvent.dylib"
BlueprintName = "Event"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_Base64"
BuildableName = "libBase64.dylib"
BlueprintName = "Base64"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_WebSocket"
BuildableName = "libWebSocket.dylib"
BlueprintName = "WebSocket"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "NO"
buildForRunning = "NO"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_Botly"
BuildableName = "Botly"
BlueprintName = "Botly"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_SlackKit"
BuildableName = "libSlackKit.dylib"
BlueprintName = "SlackKit"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_C7"
BuildableName = "libC7.dylib"
BlueprintName = "C7"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_C7"
BuildableName = "libC7.dylib"
BlueprintName = "C7"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "______Target_C7"
BuildableName = "libC7.dylib"
BlueprintName = "C7"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>SlackKit.xcscheme</key>
<dict></dict>
</dict>
<key>SuppressBuildableAutocreation</key>
<dict></dict>
</dict>
</plist>
-10
View File
@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:SlackKit.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>0.9.8</string>
<string>1.0.1</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+126
View File
@@ -0,0 +1,126 @@
//
// Attachment.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.
public struct Attachment {
public let fallback: String?
public let color: String?
public let pretext: String?
public let authorName: String?
public let authorLink: String?
public let authorIcon: String?
public let title: String?
public let titleLink: String?
public let text: String?
public let fields: [AttachmentField]?
public let imageURL: String?
public let thumbURL: String?
internal init?(attachment: [String: Any]?) {
fallback = attachment?["fallback"] as? String
color = attachment?["color"] as? String
pretext = attachment?["pretext"] as? String
authorName = attachment?["author_name"] as? String
authorLink = attachment?["author_link"] as? String
authorIcon = attachment?["author_icon"] as? String
title = attachment?["title"] as? String
titleLink = attachment?["title_link"] as? String
text = attachment?["text"] as? String
imageURL = attachment?["image_url"] as? String
thumbURL = attachment?["thumb_url"] as? String
fields = (attachment?["fields"] as? [[String: Any]])?.objectArrayFromDictionaryArray(intializer: {(field) -> AttachmentField? in
return AttachmentField(field: field)
})
}
public init?(fallback: String, title:String, colorHex: String? = nil, pretext: String? = nil, authorName: String? = nil, authorLink: String? = nil, authorIcon: String? = nil, titleLink: String? = nil, text: String? = nil, fields: [AttachmentField]? = nil, imageURL: String? = nil, thumbURL: String? = nil) {
self.fallback = fallback
self.color = colorHex
self.pretext = pretext
self.authorName = authorName
self.authorLink = authorLink
self.authorIcon = authorIcon
self.title = title
self.titleLink = titleLink
self.text = text
self.fields = fields
self.imageURL = imageURL
self.thumbURL = thumbURL
}
internal func dictionary() -> [String: Any] {
var attachment = [String: Any]()
attachment["fallback"] = fallback
attachment["color"] = color
attachment["pretext"] = pretext
attachment["authorName"] = authorName
attachment["author_link"] = authorLink
attachment["author_icon"] = authorIcon
attachment["title"] = title
attachment["title_link"] = titleLink
attachment["text"] = text
attachment["fields"] = fieldJSONArray(fields: fields)
attachment["image_url"] = imageURL
attachment["thumb_url"] = thumbURL
return attachment
}
private func fieldJSONArray(fields: [AttachmentField]?) -> [[String: Any]] {
var returnValue = [[String: Any]]()
if let f = fields {
for field in f {
returnValue.append(field.dictionary())
}
}
return returnValue
}
}
public struct AttachmentField {
public let title: String?
public let value: String?
public let short: Bool?
internal init?(field: [String: Any]?) {
title = field?["title"] as? String
value = field?["value"] as? String
short = field?["short"] as? Bool
}
public init(title:String, value:String, short: Bool? = nil) {
self.title = title
self.value = value.slackFormatEscaping()
self.short = short
}
internal func dictionary() -> [String: Any] {
var field = [String: Any]()
field["title"] = title
field["value"] = value
field["short"] = short
return field
}
}
+3 -3
View File
@@ -25,12 +25,12 @@ public struct Bot {
public let id: 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]
}
}
+9 -8
View File
@@ -43,13 +43,13 @@ public struct Channel {
internal(set) public var unread: Int?
internal(set) public var unreadCountDisplay: Int?
internal(set) public var hasPins: Bool?
internal(set) public var members = [String]()
internal(set) public var members: [String]?
// Client use
internal(set) public var pinnedItems = [Item]()
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,19 +62,20 @@ 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
latest = Message(message: channel?["latest"] as? [String: AnyObject])
unread = channel?["unread_count"] as? Int
unreadCountDisplay = channel?["unread_count_display"] as? Int
hasPins = channel?["has_pins"] as? Bool
members = channel?["members"] as? [String]
if let members = channel?["members"] as? [String] {
self.members = members
if (Message(message: channel?["latest"] as? [String: Any])?.ts == nil) {
latest = Message(ts: channel?["latest"] as? String)
} else {
latest = Message(message: channel?["latest"] as? [String: Any])
}
}
internal init?(id:String?) {
+169 -111
View File
@@ -21,10 +21,11 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Starscream
import C7
import Jay
import WebSocket
public class Client: WebSocketDelegate {
public class SlackClient {
internal(set) public var connected = false
internal(set) public var authenticated = false
@@ -50,147 +51,181 @@ public class Client: WebSocketDelegate {
public var reactionEventsDelegate: ReactionEventsDelegate?
public var teamEventsDelegate: TeamEventsDelegate?
public var subteamEventsDelegate: SubteamEventsDelegate?
public var teamProfileEventsDelegate: TeamProfileEventsDelegate?
internal var token = "SLACK_AUTH_TOKEN"
public func setAuthToken(token: String) {
self.token = token
}
public var webAPI: SlackWebAPI {
return SlackWebAPI(client: self)
return SlackWebAPI(slackClient: self)
}
internal var webSocket: WebSocket?
internal var webSocket: WebSocket.Client?
internal let api = NetworkInterface()
private var dispatcher: EventDispatcher?
internal let api = NetworkInterface()
//private let pingPongQueue = dispatch_queue_create("com.launchsoft.SlackKit", DISPATCH_QUEUE_SERIAL)
internal var ping: Double?
internal var pong: Double?
internal var pingInterval: Double?
internal var timeout: Double?
internal var reconnect: Bool?
required public init(apiToken: String) {
self.token = apiToken
}
public func connect() {
public func connect(simpleLatest: Bool? = nil, noUnreads: Bool? = nil, mpimAware: Bool? = nil, pingInterval: Double? = nil, timeout: Double? = nil, reconnect: Bool? = nil) {
self.pingInterval = pingInterval
self.timeout = timeout
self.reconnect = reconnect
dispatcher = EventDispatcher(client: self)
webAPI.rtmStart(success: {
webAPI.rtmStart(simpleLatest: simpleLatest, noUnreads: noUnreads, mpimAware: mpimAware, success: {
(response) -> Void in
self.initialSetup(response)
self.initialSetup(json: response)
if let socketURL = response["url"] as? String {
let url = NSURL(string: socketURL)
self.webSocket = WebSocket(url: url!)
self.webSocket?.delegate = self
self.webSocket?.connect()
do {
let uri = try URI(socketURL)
self.webSocket = try WebSocket.Client(uri: uri, onConnect: {(socket) in
self.setupSocket(socket: socket)
/*if let pingInterval = self.pingInterval {
self.pingRTMServerAtInterval(interval: pingInterval)
}*/
})
try self.webSocket?.connect(uri.description)
} catch _ {
}
}
}, failure:nil)
}
//MARK: - Message send
public func sendMessage(message: String, channelID: String) {
if (connected) {
if let data = formatMessageToSlackJsonString(msg: message, channel: channelID) {
let string = NSString(data: data, encoding: NSUTF8StringEncoding)
webSocket?.writeString(string as! String)
}
}
//TODO: Currently Unsupported
/*public func disconnect() {
//webSocket?.disconnect()
}
private func formatMessageToSlackJsonString(message: (msg: String, channel: String)) -> NSData? {
let json: [String: AnyObject] = [
"id": NSDate().timeIntervalSince1970,
"type": "message",
"channel": message.channel,
"text": message.msg.slackFormatEscaping()
]
addSentMessage(json)
do {
let data = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)
return data
//MARK: - RTM Message send
public func sendMessage(message: String, channelID: String) {
if (connected) {
if let data = formatMessageToSlackJsonString(message: message, channel: channelID) {
if let string = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
//webSocket?.writeString(string)
}
}
}
catch _ {
}*/
private func formatMessageToSlackJsonString(message: String, channel: String) -> Data? {
let json: [String: Any] = [
"id": Time.slackTimestamp,
"type": "message",
"channel": channel,
"text": message.slackFormatEscaping()
]
do {
let bytes = try Jay().dataFromJson(json)
return Data(bytes)
} catch {
return nil
}
}
private func addSentMessage(dictionary: [String: AnyObject]) {
private func addSentMessage(dictionary: [String: Any]) {
var message = dictionary
let ts = message["id"] as? NSNumber
message.removeValueForKey("id")
message["ts"] = ts?.stringValue
let ts = message["id"] as? Int
message.removeValue(forKey:"id")
message["ts"] = "\(ts)"
message["user"] = self.authenticatedUser?.id
sentMessages[ts!.stringValue] = Message(message: message)
sentMessages["\(ts)"] = Message(message: 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, {
if self.connected && self.timeoutCheck() {
self.sendRTMPing()
self.pingRTMServerAtInterval(interval: interval)
} else {
//self.disconnect()
}
})
}
private func sendRTMPing() {
if connected {
let json: [String: Any] = [
"id": NSDate().slackTimestamp(),
"type": "ping",
]
do {
let data = try NSJSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
let string = NSString(data: data, encoding: NSUTF8StringEncoding)
if let writePing = string as? String {
ping = json["id"] as? Double
//webSocket?.writeString(writePing)
}
}
catch _ {
}
}
}
private func timeoutCheck() -> Bool {
if let pong = pong, ping = ping, timeout = timeout {
if pong - ping < timeout {
return true
} else {
return false
}
// Ping-pong or timeout not configured
} else {
return true
}
}*/
//MARK: - Client setup
internal 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])
enumerateUsers(json["users"] as? Array)
enumerateChannels(json["channels"] as? Array)
enumerateGroups(json["groups"] as? Array)
enumerateMPIMs(json["mpims"] as? Array)
enumerateIMs(json["ims"] as? Array)
enumerateBots(json["bots"] as? Array)
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(array: json["users"] as? Array) { (user) in self.addUser(aUser: user) }
enumerateObjects(array: json["channels"] as? Array) { (channel) in self.addChannel(aChannel: channel) }
enumerateObjects(array: json["groups"] as? Array) { (group) in self.addChannel(aChannel: group) }
enumerateObjects(array: json["mpims"] as? Array) { (mpim) in self.addChannel(aChannel: mpim) }
enumerateObjects(array: json["ims"] as? Array) { (ims) in self.addChannel(aChannel: ims) }
enumerateObjects(array: json["bots"] as? Array) { (bots) in self.addBot(aBot: bots) }
enumerateSubteams(subteams: json["subteams"] as? [String: Any])
}
internal func enumerateUsers(users: [AnyObject]?) {
if let users = users {
for user in users {
let u = User(user: user as? [String: AnyObject])
self.users[u!.id!] = u
}
private func addUser(aUser: [String: Any]) {
if let user = User(user: aUser), id = user.id {
users[id] = user
}
}
internal func enumerateChannels(channels: [AnyObject]?) {
if let channels = channels {
for channel in channels {
let c = Channel(channel: channel as? [String: AnyObject])
self.channels[c!.id!] = c
}
private func addChannel(aChannel: [String: Any]) {
if let channel = Channel(channel: aChannel), id = channel.id {
channels[id] = channel
}
}
internal func enumerateGroups(groups: [AnyObject]?) {
if let groups = groups {
for group in groups {
let g = Channel(channel: group as? [String: AnyObject])
self.channels[g!.id!] = g
}
private func addBot(aBot: [String: Any]) {
if let bot = Bot(bot: aBot), id = bot.id {
bots[id] = bot
}
}
internal func enumerateIMs(ims: [AnyObject]?) {
if let ims = ims {
for im in ims {
let i = Channel(channel: im as? [String: AnyObject])
self.channels[i!.id!] = i
}
}
}
internal func enumerateMPIMs(mpims: [AnyObject]?) {
if let mpims = mpims {
for mpim in mpims {
let m = Channel(channel: mpim as? [String: AnyObject])
self.channels[m!.id!] = m
}
}
}
internal func enumerateBots(bots: [AnyObject]?) {
if let bots = bots {
for bot in bots {
let b = Bot(bot: bot as? [String: AnyObject])
self.bots[b!.id!] = b
}
}
}
internal 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
@@ -205,30 +240,53 @@ public class Client: WebSocketDelegate {
}
}
// MARK: - WebSocketDelegate
public func websocketDidConnect(socket: WebSocket) {}
public func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
connected = false
authenticated = false
webSocket = nil
if let delegate = slackEventsDelegate {
delegate.clientDisconnected()
// MARK: - Utilities
private func enumerateObjects(array: [Any]?, initalizer: ([String: Any])-> Void) {
if let array = array {
for object in array {
if let dictionary = object as? [String: Any] {
initalizer(dictionary)
}
}
}
}
public func websocketDidReceiveMessage(socket: WebSocket, text: String) {
guard let data = text.dataUsingEncoding(NSUTF8StringEncoding) else {
return
// MARK: - WebSocket
private func setupSocket(socket: Socket) {
socket.onText {(message) in
self.websocketDidReceive(message: message)
}
socket.onPing { (data) in try socket.pong() }
socket.onPong { (data) in try socket.ping() }
socket.onClose{ (code: CloseCode?, reason: String?) in
self.websocketDidDisconnect(closeCode: code, error: reason)
}
}
private func websocketDidReceive(message: String) {
do {
try dispatcher?.dispatch(NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! [String: AnyObject])
let json = try Jay().jsonFromData(message.data.bytes)
if let event = json as? [String: Any] {
dispatcher?.dispatch(event:event)
}
}
catch _ {
}
}
public func websocketDidReceiveData(socket: WebSocket, data: NSData) {}
private func websocketDidDisconnect(closeCode: CloseCode?, error: String?) {
connected = false
authenticated = false
webSocket = nil
dispatcher = nil
authenticatedUser = nil
slackEventsDelegate?.clientDisconnected()
if reconnect == true {
connect(pingInterval: pingInterval, timeout: timeout, reconnect: reconnect)
}
}
}
+83 -32
View File
@@ -21,26 +21,22 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import C7
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
extension Client {
extension SlackClient {
//MARK: - User & Channel
public func getChannelOrUserIdByName(name: String) -> String? {
if (name[name.startIndex] == "@") {
return getUserIdByName(name)
} else if (name[name.startIndex] == "C") {
return getChannelIDByName(name)
}
return nil
}
public func getChannelIDByName(name: String) -> String? {
return channels.filter{$0.1.name == stripString(name)}.first?.0
return channels.filter{$0.1.name == stripString(string: name)}.first?.0
}
public func getUserIdByName(name: String) -> String? {
return users.filter{$0.1.name == stripString(name)}.first?.0
public func getUserIDByName(name: String) -> String? {
return users.filter{$0.1.name == stripString(string: name)}.first?.0
}
public func getImIDForUserWithID(id: String, success: (imID: String?)->Void, failure: (error: SlackError)->Void) {
@@ -49,18 +45,43 @@ extension Client {
if let channel = channel {
success(imID: channel.0)
} else {
webAPI.openIM(id, success: success, failure: failure)
webAPI.openIM(userID: id, success: success, failure: failure)
}
}
//MARK: - Utilities
internal func stripString(var string: String) -> String {
if string[string.startIndex] == "@" {
string = string.substringFromIndex(string.startIndex.advancedBy(1))
} else if string[string.startIndex] == "#" {
string = string.substringFromIndex(string.startIndex.advancedBy(1))
internal func stripString(string: String) -> String? {
var strippedString = string
if string[string.startIndex] == "@" || string[string.startIndex] == "#" {
strippedString.characters.remove(at: string.startIndex.advanced(by:1))
}
return string
return strippedString
}
}
public enum AttachmentColor: String {
case Good = "good"
case Warning = "warning"
case Danger = "danger"
}
public typealias Time=Double
public extension Double {
static func slackTimestamp() -> Double {
#if os(Linux)
return Double(time(nil))
#else
var clock: clock_serv_t = clock_serv_t()
var timeSpecBuffer: mach_timespec_t = mach_timespec_t(tv_sec: 0, tv_nsec: 0)
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock)
clock_get_time(clock, &timeSpecBuffer)
mach_port_deallocate(mach_task_self_, clock)
return Double(timeSpecBuffer.tv_sec) + Double(timeSpecBuffer.tv_nsec) * 0.000000001
#endif
}
}
@@ -68,18 +89,48 @@ extension Client {
internal extension String {
func slackFormatEscaping() -> String {
var escapedString = stringByReplacingOccurrencesOfString("&", withString: "&amp;")
escapedString = stringByReplacingOccurrencesOfString("<", withString: "&lt;")
escapedString = stringByReplacingOccurrencesOfString(">", withString: "&gt;")
var escapedString = self
escapedString.replace(string: "&", with: "&amp;")
escapedString.replace(string: "<", with: "&lt;")
escapedString.replace(string: ">", with: "&gt;")
return escapedString
}
}
public extension NSDate {
func slackTimestamp() -> String {
return NSNumber(double: timeIntervalSince1970).stringValue
}
}
public extension String {
func contains(query: String, caseSensitive: Bool = false) -> Bool {
if query.isEmpty { return true }
let (s, q) = caseSensitive ? (self, query) : (self.lowercased(), query.lowercased())
var chars = s.characters; let qchars = q.characters
while !chars.isEmpty {
if chars.starts(with: qchars) { return true }
chars.removeFirst()
}
return false
}
func prefixedBy(query: String, caseSensitive: Bool = false) -> Bool {
let (s, q) = caseSensitive ? (self, query) : (self.lowercased(), query.lowercased())
return s.characters.starts(with: q.characters)
}
}
internal extension Array {
func objectArrayFromDictionaryArray<T>(intializer:([String: Any])->T?) -> [T] {
var returnValue = [T]()
for object in self {
if let dictionary = object as? [String: Any] {
if let value = intializer(dictionary) {
returnValue.append(value)
}
}
}
return returnValue
}
}
+27 -18
View File
@@ -62,6 +62,7 @@ internal enum EventType: String {
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"
@@ -78,10 +79,14 @@ internal enum EventType: String {
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"
@@ -132,14 +137,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?
@@ -148,12 +153,14 @@ internal struct Event {
let file: File?
let message: Message?
let nestedMessage: Message?
let itemUser: String?
let item: Item?
let dndStatus: DoNotDisturbStatus?
let subteam: UserGroup?
let subteamID: String?
var profile: CustomProfile?
init(event:[String: AnyObject]) {
init(event:[String: Any]) {
if let eventType = event["type"] as? String {
type = EventType(rawValue:eventType)
} else {
@@ -179,39 +186,41 @@ 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])
item = Item(item: event["item"] as? [String: AnyObject])
subteam = UserGroup(userGroup: event["subteam"] 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: 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])
nestedMessage = Message(message: event["message"] as? [String: Any])
profile = CustomProfile(profile: event["profile"] as? [String: Any])
// Comment, Channel, User, and File can come across as Strings or Dictionaries
if (Comment(comment: event["comment"] as? [String: AnyObject])?.id == nil) {
if (Comment(comment: event["comment"] as? [String: Any])?.id == nil) {
comment = Comment(id: event["comment"] as? String)
} else {
comment = Comment(comment: event["comment"] as? [String: AnyObject])
comment = Comment(comment: event["comment"] as? [String: Any])
}
if (User(user: event["user"] as? [String: AnyObject])?.id == nil) {
if (User(user: event["user"] as? [String: Any])?.id == nil) {
user = User(id: event["user"] as? String)
} else {
user = User(user: event["user"] as? [String: AnyObject])
user = User(user: event["user"] as? [String: Any])
}
if (File(file: event["file"] as? [String: AnyObject])?.id == nil) {
if (File(file: event["file"] as? [String: Any])?.id == nil) {
file = File(id: event["file"] as? String)
} else {
file = File(file: event["file"] as? [String: AnyObject])
file = File(file: event["file"] as? [String: Any])
}
if (Channel(channel: event["channel"] as? [String: AnyObject])?.id == nil) {
if (Channel(channel: event["channel"] as? [String: Any])?.id == nil) {
channel = Channel(id: event["channel"] as? String)
} else {
channel = Channel(channel: event["channel"] as? [String: AnyObject])
channel = Channel(channel: event["channel"] as? [String: Any])
}
}
+10 -6
View File
@@ -21,12 +21,10 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public protocol SlackEventsDelegate {
func clientConnected()
func clientDisconnected()
func preferenceChanged(preference: String, value: AnyObject)
func preferenceChanged(preference: String, value: Any)
func userChanged(user: User)
func presenceChanged(user: User?, presence: String?)
func manualPresenceChanged(user: User?, presence: String?)
@@ -80,14 +78,14 @@ public protocol StarEventsDelegate {
}
public protocol ReactionEventsDelegate {
func reactionAdded(reaction: String?, item: Item?)
func reactionRemoved(reaction: String?, item: Item?)
func reactionAdded(reaction: String?, item: Item?, itemUser: String?)
func reactionRemoved(reaction: String?, item: Item?, itemUser: String?)
}
public protocol TeamEventsDelegate {
func teamJoined(user: User)
func teamPlanChanged(plan: String)
func teamPreferencesChanged(preference: String, value: AnyObject)
func teamPreferencesChanged(preference: String, value: Any)
func teamNameChanged(name: String)
func teamDomainChanged(domain: String)
func teamEmailDomainChanged(domain: String)
@@ -99,3 +97,9 @@ public protocol SubteamEventsDelegate {
func subteamSelfAdded(subteamID: String)
func subteamSelfRemoved(subteamID: String)
}
public protocol TeamProfileEventsDelegate {
func teamProfileChanged(profile: CustomProfile?)
func teamProfileDeleted(profile: CustomProfile?)
func teamProfileReordered(profile: CustomProfile?)
}
+72 -58
View File
@@ -22,128 +22,142 @@
// THE SOFTWARE.
internal class EventDispatcher {
let client: Client
let client: SlackClient
let handler: EventHandler
required init(client: Client) {
required init(client: SlackClient) {
self.client = client
handler = EventHandler(client: client)
}
func dispatch(event: [String: AnyObject]) {
func dispatch(event: [String: Any]) {
let event = Event(event: event)
if let type = event.type {
switch type {
case .Hello:
handler.connected()
case .Ok:
handler.messageSent(event)
handler.messageSent(event: event)
case .Message:
if (event.subtype != nil) {
messageDispatcher(event)
messageDispatcher(event: event)
} else {
handler.messageReceived(event)
handler.messageReceived(event: event)
}
case .UserTyping:
handler.userTyping(event)
handler.userTyping(event: event)
case .ChannelMarked, .IMMarked, .GroupMarked:
handler.channelMarked(event)
handler.channelMarked(event: event)
case .ChannelCreated, .IMCreated:
handler.channelCreated(event)
handler.channelCreated(event: event)
case .ChannelJoined, .GroupJoined:
handler.channelJoined(event)
handler.channelJoined(event: event)
case .ChannelLeft, .GroupLeft:
handler.channelLeft(event)
handler.channelLeft(event: event)
case .ChannelDeleted:
handler.channelDeleted(event)
handler.channelDeleted(event: event)
case .ChannelRenamed, .GroupRename:
handler.channelRenamed(event)
handler.channelRenamed(event: event)
case .ChannelArchive, .GroupArchive:
handler.channelArchived(event, archived: true)
handler.channelArchived(event: event, archived: true)
case .ChannelUnarchive, .GroupUnarchive:
handler.channelArchived(event, archived: false)
handler.channelArchived(event: event, archived: false)
case .ChannelHistoryChanged, .IMHistoryChanged, .GroupHistoryChanged:
handler.channelHistoryChanged(event)
handler.channelHistoryChanged(event: event)
case .DNDUpdated:
handler.doNotDisturbUpdated(event)
handler.doNotDisturbUpdated(event: event)
case .DNDUpatedUser:
handler.doNotDisturbUserUpdated(event)
handler.doNotDisturbUserUpdated(event: event)
case .IMOpen, .GroupOpen:
handler.open(event, open: true)
handler.open(event: event, open: true)
case .IMClose, .GroupClose:
handler.open(event, open: false)
handler.open(event: event, open: false)
case .FileCreated:
handler.processFile(event)
handler.processFile(event: event)
case .FileShared:
handler.processFile(event)
handler.processFile(event: event)
case .FileUnshared:
handler.processFile(event)
handler.processFile(event: event)
case .FilePublic:
handler.processFile(event)
handler.processFile(event: event)
case .FilePrivate:
handler.filePrivate(event)
handler.filePrivate(event: event)
case .FileChanged:
handler.processFile(event)
handler.processFile(event: event)
case .FileDeleted:
handler.deleteFile(event)
handler.deleteFile(event: event)
case .FileCommentAdded:
handler.fileCommentAdded(event)
handler.fileCommentAdded(event: event)
case .FileCommentEdited:
handler.fileCommentEdited(event)
handler.fileCommentEdited(event: event)
case .FileCommentDeleted:
handler.fileCommentDeleted(event)
handler.fileCommentDeleted(event: event)
case .PinAdded:
handler.pinAdded(event)
handler.pinAdded(event: event)
case .PinRemoved:
handler.pinRemoved(event)
handler.pinRemoved(event: event)
case .Pong:
handler.pong(event: event)
case .PresenceChange:
handler.presenceChange(event)
handler.presenceChange(event: event)
case .ManualPresenceChange:
handler.manualPresenceChange(event)
handler.manualPresenceChange(event: event)
case .PrefChange:
handler.changePreference(event)
handler.changePreference(event: event)
case .UserChange:
handler.userChange(event)
handler.userChange(event: event)
case .TeamJoin:
handler.teamJoin(event)
handler.teamJoin(event: event)
case .StarAdded:
handler.itemStarred(event, star: true)
handler.itemStarred(event: event, star: true)
case .StarRemoved:
handler.itemStarred(event, star: false)
handler.itemStarred(event: event, star: false)
case .ReactionAdded:
handler.addedReaction(event)
handler.addedReaction(event: event)
case .ReactionRemoved:
handler.removedReaction(event)
handler.removedReaction(event: event)
case .EmojiChanged:
handler.emojiChanged(event)
handler.emojiChanged(event: event)
case .CommandsChanged:
// Not implemented per Slack documentation.
// 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:
handler.teamPlanChange(event)
handler.teamPlanChange(event: event)
case .TeamPrefChange:
handler.teamPreferenceChange(event)
handler.teamPreferenceChange(event: event)
case .TeamRename:
handler.teamNameChange(event)
handler.teamNameChange(event: event)
case .TeamDomainChange:
handler.teamDomainChange(event)
handler.teamDomainChange(event: event)
case .EmailDomainChange:
handler.emailDomainChange(event)
handler.emailDomainChange(event: event)
case .TeamProfileChange:
handler.teamProfileChange(event: event)
case .TeamProfileDelete:
handler.teamProfileDeleted(event: event)
case .TeamProfileReorder:
handler.teamProfileReordered(event: event)
case .BotAdded:
handler.bot(event)
handler.bot(event: event)
case .BotChanged:
handler.bot(event)
handler.bot(event: event)
case .AccountsChanged:
// Not implemented per Slack documentation.
// 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:
client.connect()
client.connect(pingInterval: client.pingInterval, timeout: client.timeout, reconnect: client.reconnect)
case .ReconnectURL:
// The reconnect_url event is currently unsupported and experimental.
break
case .SubteamCreated, .SubteamUpdated:
handler.subteam(event)
handler.subteam(event: event)
case .SubteamSelfAdded:
handler.subteamAddedSelf(event)
handler.subteamAddedSelf(event: event)
case.SubteamSelfRemoved:
handler.subteamRemovedSelf(event)
handler.subteamRemovedSelf(event: event)
case .Error:
print("Error: \(event)")
break
@@ -155,11 +169,11 @@ internal class EventDispatcher {
let subtype = MessageSubtype(rawValue: event.subtype!)!
switch subtype {
case .MessageChanged:
handler.messageChanged(event)
handler.messageChanged(event: event)
case .MessageDeleted:
handler.messageDeleted(event)
handler.messageDeleted(event: event)
default:
handler.messageReceived(event)
handler.messageReceived(event: event)
}
}
+110 -67
View File
@@ -21,11 +21,9 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
internal class EventHandler {
let client: Client
required init(client: Client) {
let client: SlackClient
required init(client: SlackClient) {
self.client = client
}
@@ -38,16 +36,20 @@ internal class EventHandler {
}
}
//MARK: - Messages
//MARK: - Pong
func pong(event: Event) {
client.pong = event.replyTo
}
//MARK: - Messages
func messageSent(event: Event) {
if let reply = event.replyTo, message = client.sentMessages[NSNumber(double: reply).stringValue], channel = message.channel, ts = message.ts {
if let reply = event.replyTo, message = client.sentMessages["\(reply)"], channel = message.channel, ts = message.ts {
message.ts = event.ts
message.text = event.text
client.channels[channel]?.messages[ts] = message
if let delegate = client.messageEventsDelegate {
delegate.messageSent(message)
delegate.messageSent(message: message)
}
}
}
@@ -57,7 +59,7 @@ internal class EventHandler {
client.channels[id]?.messages[ts] = message
if let delegate = client.messageEventsDelegate {
delegate.messageReceived(message)
delegate.messageReceived(message: message)
}
}
}
@@ -67,7 +69,7 @@ internal class EventHandler {
client.channels[id]?.messages[ts] = nested
if let delegate = client.messageEventsDelegate {
delegate.messageChanged(nested)
delegate.messageChanged(message: nested)
}
}
}
@@ -75,10 +77,10 @@ internal class EventHandler {
func messageDeleted(event: Event) {
if let id = event.channel?.id, key = event.message?.deletedTs {
let message = client.channels[id]?.messages[key]
client.channels[id]?.messages.removeValueForKey(key)
client.channels[id]?.messages.removeValue(forKey:key)
if let delegate = client.messageEventsDelegate {
delegate.messageDeleted(message)
delegate.messageDeleted(message: message)
}
}
}
@@ -91,17 +93,17 @@ internal class EventHandler {
client.channels[channelID]?.usersTyping.append(userID)
if let delegate = client.channelEventsDelegate {
delegate.userTyping(event.channel, user: event.user)
delegate.userTyping(channel: event.channel, user: event.user)
}
}
}
let timeout = dispatch_time(DISPATCH_TIME_NOW, Int64(5.0 * Double(NSEC_PER_SEC)))
/*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.client.channels[channelID]?.usersTyping.indexOf(userID) {
self.client.channels[channelID]?.usersTyping.removeAtIndex(index)
if let index = self.client.channels[channelID]?.usersTyping.index(of:userID) {
self.client.channels[channelID]?.usersTyping.remove(at: index)
}
}
}*/
}
}
@@ -110,7 +112,7 @@ internal class EventHandler {
client.channels[id]?.lastRead = event.ts
if let delegate = client.channelEventsDelegate {
delegate.channelMarked(channel, timestamp: event.ts)
delegate.channelMarked(channel: channel, timestamp: event.ts)
}
}
//TODO: Recalculate unreads
@@ -121,17 +123,17 @@ internal class EventHandler {
client.channels[id] = channel
if let delegate = client.channelEventsDelegate {
delegate.channelCreated(channel)
delegate.channelCreated(channel: channel)
}
}
}
func channelDeleted(event: Event) {
if let channel = event.channel, id = channel.id {
client.channels.removeValueForKey(id)
client.channels.removeValue(forKey:id)
if let delegate = client.channelEventsDelegate {
delegate.channelDeleted(channel)
delegate.channelDeleted(channel: channel)
}
}
}
@@ -141,18 +143,18 @@ internal class EventHandler {
client.channels[id] = event.channel
if let delegate = client.channelEventsDelegate {
delegate.channelJoined(channel)
delegate.channelJoined(channel: channel)
}
}
}
func channelLeft(event: Event) {
if let channel = event.channel, id = channel.id, userID = client.authenticatedUser?.id {
if let index = client.channels[id]?.members.indexOf(userID) {
client.channels[id]?.members.removeAtIndex(index)
if let index = client.channels[id]?.members?.index(of:userID) {
client.channels[id]?.members?.remove(at: index)
if let delegate = client.channelEventsDelegate {
delegate.channelLeft(channel)
delegate.channelLeft(channel: channel)
}
}
}
@@ -163,7 +165,7 @@ internal class EventHandler {
client.channels[id]?.name = channel.name
if let delegate = client.channelEventsDelegate {
delegate.channelRenamed(channel)
delegate.channelRenamed(channel: channel)
}
}
}
@@ -173,7 +175,7 @@ internal class EventHandler {
client.channels[id]?.isArchived = archived
if let delegate = client.channelEventsDelegate {
delegate.channelArchived(channel)
delegate.channelArchived(channel: channel)
}
}
}
@@ -183,7 +185,7 @@ internal class EventHandler {
//TODO: Reload chat history if there are any cached messages before latest
if let delegate = client.channelEventsDelegate {
delegate.channelHistoryChanged(channel)
delegate.channelHistoryChanged(channel: channel)
}
}
}
@@ -194,7 +196,7 @@ internal class EventHandler {
client.authenticatedUser?.doNotDisturbStatus = dndStatus
if let delegate = client.doNotDisturbEventsDelegate {
delegate.doNotDisturbUpdated(dndStatus)
delegate.doNotDisturbUpdated(dndStatus: dndStatus)
}
}
}
@@ -204,7 +206,7 @@ internal class EventHandler {
client.users[id]?.doNotDisturbStatus = dndStatus
if let delegate = client.doNotDisturbEventsDelegate {
delegate.doNotDisturbUserUpdated(dndStatus, user: user)
delegate.doNotDisturbUserUpdated(dndStatus: dndStatus, user: user)
}
}
}
@@ -215,7 +217,7 @@ internal class EventHandler {
client.channels[id]?.isOpen = open
if let delegate = client.groupEventsDelegate {
delegate.groupOpened(channel)
delegate.groupOpened(group: channel)
}
}
}
@@ -232,7 +234,7 @@ internal class EventHandler {
client.files[id] = file
if let delegate = client.fileEventsDelegate {
delegate.fileProcessed(file)
delegate.fileProcessed(file: file)
}
}
}
@@ -242,7 +244,7 @@ internal class EventHandler {
client.files[id]?.isPublic = false
if let delegate = client.fileEventsDelegate {
delegate.fileMadePrivate(file)
delegate.fileMadePrivate(file: file)
}
}
}
@@ -250,11 +252,11 @@ internal class EventHandler {
func deleteFile(event: Event) {
if let file = event.file, id = file.id {
if client.files[id] != nil {
client.files.removeValueForKey(id)
client.files.removeValue(forKey:id)
}
if let delegate = client.fileEventsDelegate {
delegate.fileDeleted(file)
delegate.fileDeleted(file: file)
}
}
}
@@ -264,7 +266,7 @@ internal class EventHandler {
client.files[id]?.comments[commentID] = comment
if let delegate = client.fileEventsDelegate {
delegate.fileCommentAdded(file, comment: comment)
delegate.fileCommentAdded(file: file, comment: comment)
}
}
}
@@ -274,17 +276,17 @@ internal class EventHandler {
client.files[id]?.comments[commentID]?.comment = comment.comment
if let delegate = client.fileEventsDelegate {
delegate.fileCommentEdited(file, comment: comment)
delegate.fileCommentEdited(file: file, comment: comment)
}
}
}
func fileCommentDeleted(event: Event) {
if let file = event.file, id = file.id, comment = event.comment, commentID = comment.id {
client.files[id]?.comments.removeValueForKey(commentID)
client.files[id]?.comments.removeValue(forKey:commentID)
if let delegate = client.fileEventsDelegate {
delegate.fileCommentDeleted(file, comment: comment)
delegate.fileCommentDeleted(file: file, comment: comment)
}
}
}
@@ -295,7 +297,7 @@ internal class EventHandler {
client.channels[id]?.pinnedItems.append(item)
if let delegate = client.pinEventsDelegate {
delegate.itemPinned(item, channel: client.channels[id])
delegate.itemPinned(item: item, channel: client.channels[id])
}
}
}
@@ -307,7 +309,7 @@ internal class EventHandler {
}
if let delegate = client.pinEventsDelegate {
delegate.itemUnpinned(event.item, channel: client.channels[id])
delegate.itemUnpinned(item: event.item, channel: client.channels[id])
}
}
}
@@ -317,17 +319,17 @@ internal class EventHandler {
if let item = event.item, type = item.type {
switch type {
case "message":
starMessage(item, star: star)
starMessage(item: item, star: star)
case "file":
starFile(item, star: star)
starFile(item: item, star: star)
case "file_comment":
starComment(item)
starComment(item: item)
default:
break
}
if let delegate = client.starEventsDelegate {
delegate.itemStarred(item, star: star)
delegate.itemStarred(item: item, star: star)
}
}
}
@@ -397,7 +399,7 @@ internal class EventHandler {
}
if let delegate = client.reactionEventsDelegate {
delegate.reactionAdded(event.reaction, item: event.item)
delegate.reactionAdded(reaction: event.reaction, item: event.item, itemUser: event.itemUser)
}
}
}
@@ -409,29 +411,29 @@ internal class EventHandler {
if let channel = item.channel, ts = item.ts {
if let message = client.channels[channel]?.messages[ts] {
if (message.reactions[key]) != nil {
message.reactions[key]?.users.removeValueForKey(userID)
message.reactions[key]?.users.removeValue(forKey:userID)
}
if (message.reactions[key]?.users.count == 0) {
message.reactions.removeValueForKey(key)
message.reactions.removeValue(forKey:key)
}
}
}
case "file":
if let itemFile = item.file, id = itemFile.id, file = client.files[id] {
if file.reactions[key] != nil {
client.files[id]?.reactions[key]?.users.removeValueForKey(userID)
client.files[id]?.reactions[key]?.users.removeValue(forKey:userID)
}
if client.files[id]?.reactions[key]?.users.count == 0 {
client.files[id]?.reactions.removeValueForKey(key)
client.files[id]?.reactions.removeValue(forKey:key)
}
}
case "file_comment":
if let id = item.file?.id, file = client.files[id], commentID = item.fileCommentID {
if file.comments[commentID]?.reactions[key] != nil {
client.files[id]?.comments[commentID]?.reactions[key]?.users.removeValueForKey(userID)
client.files[id]?.comments[commentID]?.reactions[key]?.users.removeValue(forKey:userID)
}
if client.files[id]?.comments[commentID]?.reactions[key]?.users.count == 0 {
client.files[id]?.comments[commentID]?.reactions.removeValueForKey(key)
client.files[id]?.comments[commentID]?.reactions.removeValue(forKey:key)
}
}
break
@@ -440,7 +442,7 @@ internal class EventHandler {
}
if let delegate = client.reactionEventsDelegate {
delegate.reactionAdded(event.reaction, item: event.item)
delegate.reactionAdded(reaction: event.reaction, item: event.item, itemUser: event.itemUser)
}
}
}
@@ -451,7 +453,7 @@ internal class EventHandler {
client.authenticatedUser?.preferences?[name] = event.value
if let delegate = client.slackEventsDelegate, value = event.value {
delegate.preferenceChanged(name, value: value)
delegate.preferenceChanged(preference: name, value: value)
}
}
}
@@ -464,7 +466,7 @@ internal class EventHandler {
client.users[id]?.preferences = preferences
if let delegate = client.slackEventsDelegate {
delegate.userChanged(user)
delegate.userChanged(user: user)
}
}
}
@@ -475,7 +477,7 @@ internal class EventHandler {
client.users[id]?.presence = event.presence
if let delegate = client.slackEventsDelegate {
delegate.presenceChanged(user, presence: event.presence)
delegate.presenceChanged(user: user, presence: event.presence)
}
}
}
@@ -486,7 +488,7 @@ internal class EventHandler {
client.users[id] = user
if let delegate = client.teamEventsDelegate {
delegate.teamJoined(user)
delegate.teamJoined(user: user)
}
}
}
@@ -496,7 +498,7 @@ internal class EventHandler {
client.team?.plan = plan
if let delegate = client.teamEventsDelegate {
delegate.teamPlanChanged(plan)
delegate.teamPlanChanged(plan: plan)
}
}
}
@@ -506,7 +508,7 @@ internal class EventHandler {
client.team?.prefs?[name] = event.value
if let delegate = client.teamEventsDelegate, value = event.value {
delegate.teamPreferencesChanged(name, value: value)
delegate.teamPreferencesChanged(preference: name, value: value)
}
}
}
@@ -516,7 +518,7 @@ internal class EventHandler {
client.team?.name = name
if let delegate = client.teamEventsDelegate {
delegate.teamNameChanged(name)
delegate.teamNameChanged(name: name)
}
}
}
@@ -526,7 +528,7 @@ internal class EventHandler {
client.team?.domain = domain
if let delegate = client.teamEventsDelegate {
delegate.teamDomainChanged(domain)
delegate.teamDomainChanged(domain: domain)
}
}
}
@@ -536,7 +538,7 @@ internal class EventHandler {
client.team?.emailDomain = domain
if let delegate = client.teamEventsDelegate {
delegate.teamEmailDomainChanged(domain)
delegate.teamEmailDomainChanged(domain: domain)
}
}
}
@@ -555,7 +557,7 @@ internal class EventHandler {
client.bots[id] = bot
if let delegate = client.slackEventsDelegate {
delegate.botEvent(bot)
delegate.botEvent(bot: bot)
}
}
}
@@ -566,7 +568,7 @@ internal class EventHandler {
client.userGroups[id] = subteam
if let delegate = client.subteamEventsDelegate {
delegate.subteamEvent(subteam)
delegate.subteamEvent(userGroup: subteam)
}
}
@@ -577,27 +579,68 @@ internal class EventHandler {
client.authenticatedUser?.userGroups![subteamID] = subteamID
if let delegate = client.subteamEventsDelegate {
delegate.subteamSelfAdded(subteamID)
delegate.subteamSelfAdded(subteamID: subteamID)
}
}
}
func subteamRemovedSelf(event: Event) {
if let subteamID = event.subteamID {
client.authenticatedUser?.userGroups?.removeValueForKey(subteamID)
client.authenticatedUser?.userGroups?.removeValue(forKey:subteamID)
if let delegate = client.subteamEventsDelegate {
delegate.subteamSelfRemoved(subteamID)
delegate.subteamSelfRemoved(subteamID: subteamID)
}
}
}
//MARK: - Team Profiles
func teamProfileChange(event: Event) {
for user in client.users {
if let fields = event.profile?.fields {
for key in fields.keys {
client.users[user.0]?.profile?.customProfile?.fields[key]?.updateProfileField(profile: fields[key])
}
}
}
if let delegate = client.teamProfileEventsDelegate {
delegate.teamProfileChanged(profile: event.profile)
}
}
func teamProfileDeleted(event: Event) {
for user in client.users {
if let id = event.profile?.fields.first?.0 {
client.users[user.0]?.profile?.customProfile?.fields[id] = nil
}
}
if let delegate = client.teamProfileEventsDelegate {
delegate.teamProfileDeleted(profile: event.profile)
}
}
func teamProfileReordered(event: Event) {
for user in client.users {
if let keys = event.profile?.fields.keys {
for key in keys {
client.users[user.0]?.profile?.customProfile?.fields[key]?.ordering = event.profile?.fields[key]?.ordering
}
}
}
if let delegate = client.teamProfileEventsDelegate {
delegate.teamProfileReordered(profile: event.profile)
}
}
//MARK: - Authenticated User
func manualPresenceChange(event: Event) {
client.authenticatedUser?.presence = event.presence
if let delegate = client.slackEventsDelegate {
delegate.manualPresenceChanged(client.authenticatedUser, presence: event.presence)
delegate.manualPresenceChanged(user: client.authenticatedUser, presence: event.presence)
}
}
+5 -5
View File
@@ -62,7 +62,7 @@ public struct File {
internal(set) public var comments = [String: Comment]()
internal(set) public var reactions = [String: Reaction]()
init?(file:[String: AnyObject]?) {
public init?(file:[String: Any]?) {
id = file?["id"] as? String
created = file?["created"] as? Int
name = file?["name"] as? String
@@ -95,17 +95,17 @@ 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]
if let reactions = file?["reactions"] as? [[String: AnyObject]] {
self.reactions = Reaction.reactionsFromArray(reactions)
if let reactions = file?["reactions"] as? [[String: Any]] {
self.reactions = Reaction.reactionsFromArray(array: reactions)
}
}
init?(id:String?) {
internal init?(id:String?) {
self.id = id
created = nil
name = nil
+35 -16
View File
@@ -21,13 +21,6 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public enum ItemType: String {
case ChannelMessage = "C"
case PrivateGroupMessage = "G"
case File = "F"
case FileComments = "Fc"
}
public class Message {
public let type = "message"
@@ -39,7 +32,7 @@ public 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?
@@ -53,8 +46,9 @@ public class Message {
public let comment: Comment?
public let file: File?
internal(set) public var reactions = [String: Reaction]()
internal(set) public var attachments: [Attachment]?
init?(message: [String: AnyObject]?) {
public init?(message: [String: Any]?) {
subtype = message?["subtype"] as? String
ts = message?["ts"] as? String
user = message?["user"] as? String
@@ -63,7 +57,7 @@ public class Message {
text = message?["text"] as? String
botID = message?["bot_id"] as? String
username = message?["username"] as? String
icons = message?["icons"] as? [String: AnyObject]
icons = message?["icons"] as? [String: Any]
deletedTs = message?["deleted_ts"] as? String
purpose = message?["purpose"] as? String
topic = message?["topic"] as? String
@@ -74,14 +68,39 @@ public class Message {
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])
if let messageReactions = message?["reactions"] as? [[String: AnyObject]] {
for react in messageReactions {
let reaction = Reaction(reaction: react)
self.reactions[reaction!.name!] = reaction
comment = Comment(comment: message?["comment"] as? [String: Any])
file = File(file: message?["file"] as? [String: Any])
reactions = messageReactions(reactions: message?["reactions"] as? [[String: Any]])
attachments = (message?["attachments"] as? [[String: Any]])?.objectArrayFromDictionaryArray(intializer: {(attachment) -> Attachment? in
return Attachment(attachment: attachment)
})
}
internal init?(ts:String?) {
self.ts = ts
subtype = nil
user = nil
channel = nil
botID = nil
username = nil
icons = nil
deletedTs = nil
upload = nil
itemType = nil
comment = nil
file = nil
}
private func messageReactions(reactions: [[String: Any]]?) -> [String: Reaction] {
var returnValue = [String: Reaction]()
if let r = reactions {
for react in r {
if let reaction = Reaction(reaction: react), reactionName = reaction.name {
returnValue[reactionName] = reaction
}
}
}
return returnValue
}
}
+110 -48
View File
@@ -22,51 +22,103 @@
// THE SOFTWARE.
import Foundation
import HTTPSClient
import Jay
internal struct NetworkInterface {
private let apiUrl = "https://slack.com/api/"
private let client: HTTPSClient.Client?
internal func request(endpoint: SlackAPIEndpoint, token: String, parameters: [String: AnyObject]?, successClosure: ([String: AnyObject])->Void, errorClosure: (SlackError)->Void) {
var requestString = "\(apiUrl)\(endpoint.rawValue)?token=\(token)"
if let params = parameters {
requestString = requestString + requestStringFromParameters(params)
init() {
do {
self.client = try Client(uri: URI("https://slack.com"))
} catch {
self.client = nil
}
let request = NSURLRequest(URL: NSURL(string: requestString)!)
NSURLSession.sharedSession().dataTaskWithRequest(request) {
(data, response, internalError) -> Void in
guard let data = data else {
return
}
do {
let result = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! [String: AnyObject]
if (result["ok"] as! Bool == true) {
successClosure(result)
} else {
if let errorString = result["error"] as? String {
throw ErrorDispatcher.dispatch(errorString)
} else {
throw SlackError.UnknownError
}
}
} catch let error {
if let slackError = error as? SlackError {
errorClosure(slackError)
} else {
errorClosure(SlackError.UnknownError)
}
}
}.resume()
}
internal func uploadRequest(token: String, data: NSData, parameters: [String: AnyObject]?, successClosure: ([String: AnyObject])->Void, errorClosure: (SlackError)->Void) {
var requestString = "\(apiUrl)\(SlackAPIEndpoint.FilesUpload.rawValue)?token=\(token)"
internal func request(endpoint: SlackAPIEndpoint, token: String, parameters: [String: Any]?, successClosure: ([String: Any])->Void, errorClosure: (SlackError)->Void) {
var requestString = "\(apiUrl)\(endpoint.rawValue)?token=\(token)"
if let params = parameters {
requestString = requestString + requestStringFromParameters(params)
requestString += requestStringFromParameters(parameters: params)
}
let request = NSMutableURLRequest(URL: NSURL(string: requestString)!)
request.HTTPMethod = "POST"
do {
var response: Response?
response = try client?.get(requestString)
let data = try response?.body.becomeBuffer()
if let data = data {
let json = try Jay().jsonFromData(data.bytes)
if let result = json as? [String: Any] {
if (result["ok"] as? Bool == true) {
successClosure(result)
} else {
if let errorString = result["error"] as? String {
throw ErrorDispatcher.dispatch(error: errorString)
} else {
throw SlackError.UnknownError
}
}
}
}
} catch let error {
if let slackError = error as? SlackError {
errorClosure(slackError)
} else {
errorClosure(SlackError.UnknownError)
}
}
}
internal func postRequest(endpoint: SlackAPIEndpoint, token: String, parameters: [String: Any]?, successClosure: ([String: Any])->Void, errorClosure: (SlackError)->Void) {
let requestString = "\(apiUrl)\(endpoint.rawValue)?token=\(token)"
do {
var response: Response?
let headers: Headers = ["Content-Type": "application/x-www-form-urlencoded"]
var body = ""
if let params = parameters {
body = requestStringFromParameters(parameters: params)
} else {
body = ""
}
response = try client?.post(requestString, headers: headers, body: body)
let data = try response?.body.becomeBuffer()
if let data = data {
let json = try Jay().jsonFromData(data.bytes)
if let result = json as? [String: Any] {
if (result["ok"] as? Bool == true) {
successClosure(result)
} else {
if let errorString = result["error"] as? String {
throw ErrorDispatcher.dispatch(error: errorString)
} else {
throw SlackError.UnknownError
}
}
}
}
} catch let error {
if let slackError = error as? SlackError {
errorClosure(slackError)
} else {
errorClosure(SlackError.UnknownError)
}
}
}
//TODO: Currently Unsupported
/*internal func uploadRequest(token: String, data: NSData, parameters: [String: Any]?, successClosure: ([String: Any])->Void, errorClosure: (SlackError)->Void) {
var requestString = "\(apiUrl)\(SlackAPIEndpoint.FilesUpload.rawValue)?token=\(token)"
if let params = parameters {
requestString = requestString + requestStringFromParameters(parameters: params)
}
let request = NSMutableURLRequest(url: NSURL(string: requestString)!)
request.httpMethod = "POST"
let boundaryConstant = randomBoundary()
let contentType = "multipart/form-data; boundary=" + boundaryConstant
let boundaryStart = "--\(boundaryConstant)\r\n"
@@ -75,28 +127,28 @@ internal struct NetworkInterface {
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)!)
requestBodyData.append(boundaryStart.data(using: NSUTF8StringEncoding)!)
requestBodyData.append(contentDispositionString.data(using: NSUTF8StringEncoding)!)
requestBodyData.append(contentTypeString.data(using: NSUTF8StringEncoding)!)
requestBodyData.append(data)
requestBodyData.append("\r\n".data(using: NSUTF8StringEncoding)!)
requestBodyData.append(boundaryEnd.data(using: NSUTF8StringEncoding)!)
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
request.HTTPBody = requestBodyData
request.httpBody = requestBodyData
NSURLSession.sharedSession().dataTaskWithRequest(request) {
NSURLSession.shared().dataTask(with: request) {
(data, response, internalError) -> Void in
guard let data = data else {
return
}
do {
let result = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! [String: AnyObject]
let result = try NSJSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
if (result["ok"] as! Bool == true) {
successClosure(result)
} else {
if let errorString = result["error"] as? String {
throw ErrorDispatcher.dispatch(errorString)
throw ErrorDispatcher.dispatch(error: errorString)
} else {
throw SlackError.UnknownError
}
@@ -113,13 +165,23 @@ internal struct NetworkInterface {
private func randomBoundary() -> String {
return String(format: "slackkit.boundary.%08x%08x", arc4random(), arc4random())
}
}*/
private func requestStringFromParameters(parameters: [String: AnyObject]) -> String {
private func requestStringFromParameters(parameters: [String: Any]) -> String {
var requestString = ""
for key in parameters.keys {
if let value = parameters[key] as? String, encodedValue = value.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet()) {
requestString = requestString + "&"+key+"="+encodedValue
if let value = parameters[key] as? String {
#if os(Linux)
if let encodedValue = value.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) {
requestString += "&\(key)=\(encodedValue)"
}
#else
if let encodedValue = value.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed()) {
requestString += "&\(key)=\(encodedValue)"
}
#endif
} else if let value = parameters[key] as? Int {
requestString += "&\(key)=\(value)"
}
}
+199 -109
View File
@@ -21,7 +21,7 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Jay
internal enum SlackAPIEndpoint: String {
case APITest = "api.test"
@@ -35,7 +35,12 @@ internal enum SlackAPIEndpoint: String {
case ChatDelete = "chat.delete"
case ChatPostMessage = "chat.postMessage"
case ChatUpdate = "chat.update"
case DNDInfo = "dnd.info"
case DNDTeamInfo = "dnd.teamInfo"
case EmojiList = "emoji.list"
case FilesCommentsAdd = "files.comments.add"
case FilesCommentsEdit = "files.comments.edit"
case FilesCommentsDelete = "files.comments.delete"
case FilesDelete = "files.delete"
case FilesUpload = "files.upload"
case GroupsClose = "groups.close"
@@ -98,15 +103,16 @@ public class SlackWebAPI {
case IM = "im"
}
private let client: Client
private let client: SlackClient
required public init(client: Client) {
self.client = client
required public init(slackClient: SlackClient) {
self.client = slackClient
}
//MARK: - RTM
public func rtmStart(success success: ((response: [String: AnyObject])->Void)?, failure: FailureClosure?) {
client.api.request(.RTMStart, token: client.token, parameters: nil, successClosure: {
public func rtmStart(simpleLatest: Bool? = nil, noUnreads: Bool? = nil, mpimAware: Bool? = nil, success: ((response: [String: Any])->Void)?, failure: FailureClosure?) {
let parameters: [String: Any?] = ["simple_latest": simpleLatest, "no_unreads": noUnreads, "mpim_aware": mpimAware]
client.api.request(endpoint: .RTMStart, token: client.token, parameters: filterNilParameters(parameters: parameters), successClosure: {
(response) -> Void in
success?(response: response)
}) {(error) -> Void in
@@ -116,7 +122,7 @@ public class SlackWebAPI {
//MARK: - Auth Test
public func authenticationTest(success: ((authenticated: Bool)->Void)?, failure: FailureClosure?) {
client.api.request(.AuthTest, token: client.token, parameters: nil, successClosure: {
client.api.request(endpoint: .AuthTest, token: client.token, parameters: nil, successClosure: {
(response) -> Void in
success?(authenticated: true)
}) {(error) -> Void in
@@ -125,17 +131,17 @@ public class SlackWebAPI {
}
//MARK: - Channels
public func channelHistory(id: String, latest: String = "\(NSDate().timeIntervalSince1970)", oldest: String = "0", inclusive: Bool = false, count: Int = 100, unreads: Bool = false, success: ((history: [String: AnyObject]?)->Void)?, failure: FailureClosure?) {
history(.ChannelsHistory, id: id, latest: latest, oldest: oldest, inclusive: inclusive, count: count, unreads: unreads, success: {
public func channelHistory(id: String, latest: String = "\(Time.slackTimestamp())", oldest: String = "0", inclusive: Bool = false, count: Int = 100, unreads: Bool = false, success: ((history: History?)->Void)?, failure: FailureClosure?) {
history(endpoint: .ChannelsHistory, id: id, latest: latest, oldest: oldest, inclusive: inclusive, count: count, unreads: unreads, success: {
(history) -> Void in
success?(history:history)
success?(history: history)
}) {(error) -> Void in
failure?(error: error)
}
}
public func channelInfo(id: String, success: ((channel: Channel?)->Void)?, failure: FailureClosure?) {
info(.ChannelsInfo, type:ChannelType.Channel, id: id, success: {
info(endpoint: .ChannelsInfo, type:ChannelType.Channel, id: id, success: {
(channel) -> Void in
success?(channel: channel)
}) { (error) -> Void in
@@ -143,8 +149,8 @@ public class SlackWebAPI {
}
}
public func channelsList(excludeArchived: Bool = false, success: ((channels: [[String: AnyObject]]?)->Void)?, failure: FailureClosure?) {
list(.ChannelsList, type:ChannelType.Channel, excludeArchived: excludeArchived, success: {
public func channelsList(excludeArchived: Bool = false, success: ((channels: [Any]?)->Void)?, failure: FailureClosure?) {
list(endpoint: .ChannelsList, type:ChannelType.Channel, excludeArchived: excludeArchived, success: {
(channels) -> Void in
success?(channels: channels)
}) {(error) -> Void in
@@ -153,7 +159,7 @@ public class SlackWebAPI {
}
public func markChannel(channel: String, timestamp: String, success: ((ts: String)->Void)?, failure: FailureClosure?) {
mark(.ChannelsMark, channel: channel, timestamp: timestamp, success: {
mark(endpoint: .ChannelsMark, channel: channel, timestamp: timestamp, success: {
(ts) -> Void in
success?(ts:timestamp)
}) {(error) -> Void in
@@ -162,7 +168,7 @@ public class SlackWebAPI {
}
public func setChannelPurpose(channel: String, purpose: String, success: ((purposeSet: Bool)->Void)?, failure: FailureClosure?) {
setInfo(.ChannelsSetPurpose, type: .Purpose, channel: channel, text: purpose, success: {
setInfo(endpoint: .ChannelsSetPurpose, type: .Purpose, channel: channel, text: purpose, success: {
(purposeSet) -> Void in
success?(purposeSet: purposeSet)
}) { (error) -> Void in
@@ -171,7 +177,7 @@ public class SlackWebAPI {
}
public func setChannelTopic(channel: String, topic: String, success: ((topicSet: Bool)->Void)?, failure: FailureClosure?) {
setInfo(.ChannelsSetTopic, type: .Topic, channel: channel, text: topic, success: {
setInfo(endpoint: .ChannelsSetTopic, type: .Topic, channel: channel, text: topic, success: {
(topicSet) -> Void in
success?(topicSet: topicSet)
}) {(error) -> Void in
@@ -181,17 +187,17 @@ public class SlackWebAPI {
//MARK: - Messaging
public func deleteMessage(channel: String, ts: String, success: ((deleted: Bool)->Void)?, failure: FailureClosure?) {
let parameters: [String: AnyObject] = ["channel": channel, "ts": ts]
client.api.request(.ChatDelete, token: client.token, parameters: parameters, successClosure: { (response) -> Void in
let parameters: [String: Any] = ["channel": channel, "ts": ts]
client.api.request(endpoint: .ChatDelete, token: client.token, parameters: parameters, successClosure: { (response) -> Void in
success?(deleted: true)
}) {(error) -> Void in
failure?(error: error)
}
}
public func sendMessage(channel: String, text: String, username: String? = nil, asUser: Bool = false, parse: ParseMode = .Full, linkNames: Bool = false, attachments: [[String: AnyObject]]? = nil, unfurlLinks: Bool = false, unfurlMedia: Bool = false, iconURL: String? = nil, iconEmoji: String? = nil, success: (((ts: String?, channel: String?))->Void)?, failure: FailureClosure?) {
let parameters: [String: AnyObject?] = ["channel":channel, "text":text.slackFormatEscaping(), "as_user":asUser, "parse":parse.rawValue, "link_names":linkNames, "unfurl_links":unfurlLinks, "unfurlMedia":unfurlMedia, "username":username, "attachments":attachments, "icon_url":iconURL, "icon_emoji":iconEmoji]
client.api.request(.ChatPostMessage, token: client.token, parameters: filterNilParameters(parameters), successClosure: {
public func sendMessage(channel: String, text: String, username: String? = nil, asUser: Bool? = nil, parse: ParseMode? = nil, linkNames: Bool? = nil, attachments: [Attachment?]? = nil, unfurlLinks: Bool? = nil, unfurlMedia: Bool? = nil, iconURL: String? = nil, iconEmoji: String? = nil, success: (((ts: String?, channel: String?))->Void)?, failure: FailureClosure?) {
let parameters: [String: Any?] = ["channel":channel, "text":text.slackFormatEscaping(), "as_user":asUser, "parse":parse?.rawValue, "link_names":linkNames, "unfurl_links":unfurlLinks, "unfurlMedia":unfurlMedia, "username":username, "attachments":encodeAttachments(attachments: attachments), "icon_url":iconURL, "icon_emoji":iconEmoji]
client.api.postRequest(endpoint: .ChatPostMessage, token: client.token, parameters: filterNilParameters(parameters: parameters), successClosure: {
(response) -> Void in
success?((ts: response["ts"] as? String, response["channel"] as? String))
}) {(error) -> Void in
@@ -199,9 +205,9 @@ public class SlackWebAPI {
}
}
public func updateMessage(channel: String, ts: String, message: String, attachments: [[String: AnyObject]]? = nil, parse:ParseMode = .None, linkNames: Bool = false, success: ((updated: Bool)->Void)?, failure: FailureClosure?) {
let parameters: [String: AnyObject?] = ["channel": channel, "ts": ts, "text": message.slackFormatEscaping(), "parse": parse.rawValue, "link_names": linkNames, "attachments":attachments]
client.api.request(.ChatUpdate, token: client.token, parameters: filterNilParameters(parameters), successClosure: {
public func updateMessage(channel: String, ts: String, message: String, attachments: [Attachment?]? = nil, parse:ParseMode = .None, linkNames: Bool = false, success: ((updated: Bool)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any?] = ["channel": channel, "ts": ts, "text": message.slackFormatEscaping(), "parse": parse.rawValue, "link_names": linkNames, "attachments":encodeAttachments(attachments: attachments)]
client.api.postRequest(endpoint: .ChatUpdate, token: client.token, parameters: filterNilParameters(parameters: parameters), successClosure: {
(response) -> Void in
success?(updated: true)
}) {(error) -> Void in
@@ -209,11 +215,32 @@ public class SlackWebAPI {
}
}
//MARK: - Emoji
public func emojiList(success: ((emojiList: [String: AnyObject]?)->Void)?, failure: FailureClosure?) {
client.api.request(.EmojiList, token: client.token, parameters: nil, successClosure: {
//MARK: - Do Not Disturb
public func dndInfo(user: String? = nil, success: ((status: DoNotDisturbStatus?)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any?] = ["user": user]
client.api.request(endpoint: .DNDInfo, token: client.token, parameters: filterNilParameters(parameters: parameters), successClosure: {
(response) -> Void in
success?(emojiList: response["emoji"] as? [String: AnyObject])
success?(status: DoNotDisturbStatus(status: response))
}) {(error) -> Void in
failure?(error: error)
}
}
public func dndTeamInfo(users: [String]? = nil, success: ((statuses: [String: DoNotDisturbStatus]?)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any?] = ["users":users?.joined(separator: ",")]
client.api.request(endpoint: .DNDTeamInfo, token: client.token, parameters: filterNilParameters(parameters: parameters), successClosure: {
(response) -> Void in
success?(statuses: self.enumerateDNDStauses(statuses: response["users"] as? [String: Any]))
}) {(error) -> Void in
failure?(error: error)
}
}
//MARK: - Emoji
public func emojiList(success: ((emojiList: [String: Any]?)->Void)?, failure: FailureClosure?) {
client.api.request(endpoint: .EmojiList, token: client.token, parameters: nil, successClosure: {
(response) -> Void in
success?(emojiList: response["emoji"] as? [String: Any])
}) { (error) -> Void in
failure?(error: error)
}
@@ -221,8 +248,8 @@ public class SlackWebAPI {
//MARK: - Files
public func deleteFile(fileID: String, success: ((deleted: Bool)->Void)?, failure: FailureClosure?) {
let parameters = ["file":fileID]
client.api.request(.FilesDelete, token: client.token, parameters: parameters, successClosure: {
let parameters: [String: Any] = ["file":fileID]
client.api.request(endpoint: .FilesDelete, token: client.token, parameters: parameters, successClosure: {
(response) -> Void in
success?(deleted: true)
}) {(error) -> Void in
@@ -230,11 +257,43 @@ public class SlackWebAPI {
}
}
public func uploadFile(file: NSData, filename: String, filetype: String = "auto", title: String? = nil, initialComment: String? = nil, channels: [String]? = nil, success: ((file: File?)->Void)?, failure: FailureClosure?) {
let parameters: [String: AnyObject?] = ["file":file, "filename": filename, "filetype":filetype, "title":title, "initial_comment":initialComment, "channels":channels?.joinWithSeparator(",")]
client.api.uploadRequest(client.token, data: file, parameters: filterNilParameters(parameters), successClosure: {
//TODO: Currently Unsupported
/*public func uploadFile(file: NSData, filename: String, filetype: String = "auto", title: String? = nil, initialComment: String? = nil, channels: [String]? = nil, success: ((file: File?)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any?] = ["file":file, "filename": filename, "filetype":filetype, "title":title, "initial_comment":initialComment, "channels":channels?.joined(separator: ",")]
client.api.uploadRequest(token: client.token, data: file, parameters: filterNilParameters(parameters: parameters), successClosure: {
(response) -> Void in
success?(file: File(file: response["file"] as? [String: AnyObject]))
success?(file: File(file: response["file"] as? [String: Any]))
}) {(error) -> Void in
failure?(error: error)
}
}*/
//MARK: - File Comments
public func addFileComment(fileID: String, comment: String, success: ((comment: Comment?)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any] = ["file":fileID, "comment":comment.slackFormatEscaping()]
client.api.request(endpoint: .FilesCommentsAdd, token: client.token, parameters: parameters, successClosure: {
(response) -> Void in
success?(comment: Comment(comment: response["comment"] as? [String: Any]))
}) {(error) -> Void in
failure?(error: error)
}
}
public func editFileComment(fileID: String, commentID: String, comment: String, success: ((comment: Comment?)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any] = ["file":fileID, "id":commentID, "comment":comment.slackFormatEscaping()]
client.api.request(endpoint: .FilesCommentsEdit, token: client.token, parameters: parameters, successClosure: {
(response) -> Void in
success?(comment: Comment(comment: response["comment"] as? [String: Any]))
}) {(error) -> Void in
failure?(error: error)
}
}
public func deleteFileComment(fileID: String, commentID: String, success: ((deleted: Bool?)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any] = ["file":fileID, "id": commentID]
client.api.request(endpoint: .FilesCommentsDelete, token: client.token, parameters: parameters, successClosure: {
(response) -> Void in
success?(deleted: true)
}) {(error) -> Void in
failure?(error: error)
}
@@ -242,7 +301,7 @@ public class SlackWebAPI {
//MARK: - Groups
public func closeGroup(groupID: String, success: ((closed: Bool)->Void)?, failure: FailureClosure?) {
close(.GroupsClose, channelID: groupID, success: {
close(endpoint: .GroupsClose, channelID: groupID, success: {
(closed) -> Void in
success?(closed:closed)
}) {(error) -> Void in
@@ -250,8 +309,8 @@ public class SlackWebAPI {
}
}
public func groupHistory(id: String, latest: String = "\(NSDate().timeIntervalSince1970)", oldest: String = "0", inclusive: Bool = false, count: Int = 100, unreads: Bool = false, success: ((history: [String: AnyObject]?)->Void)?, failure: FailureClosure?) {
history(.GroupsHistory, id: id, latest: latest, oldest: oldest, inclusive: inclusive, count: count, unreads: unreads, success: {
public func groupHistory(id: String, latest: String = "\(Time.slackTimestamp())", oldest: String = "0", inclusive: Bool = false, count: Int = 100, unreads: Bool = false, success: ((history: History?)->Void)?, failure: FailureClosure?) {
history(endpoint: .GroupsHistory, id: id, latest: latest, oldest: oldest, inclusive: inclusive, count: count, unreads: unreads, success: {
(history) -> Void in
success?(history: history)
}) {(error) -> Void in
@@ -260,7 +319,7 @@ public class SlackWebAPI {
}
public func groupInfo(id: String, success: ((channel: Channel?)->Void)?, failure: FailureClosure?) {
info(.GroupsInfo, type:ChannelType.Group, id: id, success: {
info(endpoint: .GroupsInfo, type:ChannelType.Group, id: id, success: {
(channel) -> Void in
success?(channel: channel)
}) {(error) -> Void in
@@ -268,8 +327,8 @@ public class SlackWebAPI {
}
}
public func groupsList(excludeArchived: Bool = false, success: ((channels: [[String: AnyObject]]?)->Void)?, failure: FailureClosure?) {
list(.GroupsList, type:ChannelType.Group, excludeArchived: excludeArchived, success: {
public func groupsList(excludeArchived: Bool = false, success: ((channels: [Any]?)->Void)?, failure: FailureClosure?) {
list(endpoint: .GroupsList, type:ChannelType.Group, excludeArchived: excludeArchived, success: {
(channels) -> Void in
success?(channels: channels)
}) {(error) -> Void in
@@ -278,7 +337,7 @@ public class SlackWebAPI {
}
public func markGroup(channel: String, timestamp: String, success: ((ts: String)->Void)?, failure: FailureClosure?) {
mark(.GroupsMark, channel: channel, timestamp: timestamp, success: {
mark(endpoint: .GroupsMark, channel: channel, timestamp: timestamp, success: {
(ts) -> Void in
success?(ts: timestamp)
}) {(error) -> Void in
@@ -287,8 +346,8 @@ public class SlackWebAPI {
}
public func openGroup(channel: String, success: ((opened: Bool)->Void)?, failure: FailureClosure?) {
let parameters = ["channel":channel]
client.api.request(.GroupsOpen, token: client.token, parameters: parameters, successClosure: {
let parameters: [String: Any] = ["channel":channel]
client.api.request(endpoint: .GroupsOpen, token: client.token, parameters: parameters, successClosure: {
(response) -> Void in
success?(opened: true)
}) {(error) -> Void in
@@ -297,7 +356,7 @@ public class SlackWebAPI {
}
public func setGroupPurpose(channel: String, purpose: String, success: ((purposeSet: Bool)->Void)?, failure: FailureClosure?) {
setInfo(.GroupsSetPurpose, type: .Purpose, channel: channel, text: purpose, success: {
setInfo(endpoint: .GroupsSetPurpose, type: .Purpose, channel: channel, text: purpose, success: {
(purposeSet) -> Void in
success?(purposeSet: purposeSet)
}) {(error) -> Void in
@@ -306,7 +365,7 @@ public class SlackWebAPI {
}
public func setGroupTopic(channel: String, topic: String, success: ((topicSet: Bool)->Void)?, failure: FailureClosure?) {
setInfo(.GroupsSetTopic, type: .Topic, channel: channel, text: topic, success: {
setInfo(endpoint: .GroupsSetTopic, type: .Topic, channel: channel, text: topic, success: {
(topicSet) -> Void in
success?(topicSet: topicSet)
}) {(error) -> Void in
@@ -316,7 +375,7 @@ public class SlackWebAPI {
//MARK: - IM
public func closeIM(channel: String, success: ((closed: Bool)->Void)?, failure: FailureClosure?) {
close(.IMClose, channelID: channel, success: {
close(endpoint: .IMClose, channelID: channel, success: {
(closed) -> Void in
success?(closed: closed)
}) {(error) -> Void in
@@ -324,8 +383,8 @@ public class SlackWebAPI {
}
}
public func imHistory(id: String, latest: String = "\(NSDate().timeIntervalSince1970)", oldest: String = "0", inclusive: Bool = false, count: Int = 100, unreads: Bool = false, success: ((history: [String: AnyObject]?)->Void)?, failure: FailureClosure?) {
history(.IMHistory, id: id, latest: latest, oldest: oldest, inclusive: inclusive, count: count, unreads: unreads, success: {
public func imHistory(id: String, latest: String = "\(Time.slackTimestamp())", oldest: String = "0", inclusive: Bool = false, count: Int = 100, unreads: Bool = false, success: ((history: History?)->Void)?, failure: FailureClosure?) {
history(endpoint: .IMHistory, id: id, latest: latest, oldest: oldest, inclusive: inclusive, count: count, unreads: unreads, success: {
(history) -> Void in
success?(history: history)
}) {(error) -> Void in
@@ -333,8 +392,8 @@ public class SlackWebAPI {
}
}
public func imsList(excludeArchived: Bool = false, success: ((channels: [[String: AnyObject]]?)->Void)?, failure: FailureClosure?) {
list(.IMList, type:ChannelType.IM, excludeArchived: excludeArchived, success: {
public func imsList(excludeArchived: Bool = false, success: ((channels: [Any]?)->Void)?, failure: FailureClosure?) {
list(endpoint: .IMList, type:ChannelType.IM, excludeArchived: excludeArchived, success: {
(channels) -> Void in
success?(channels: channels)
}) {(error) -> Void in
@@ -343,7 +402,7 @@ public class SlackWebAPI {
}
public func markIM(channel: String, timestamp: String, success: ((ts: String)->Void)?, failure: FailureClosure?) {
mark(.IMMark, channel: channel, timestamp: timestamp, success: {
mark(endpoint: .IMMark, channel: channel, timestamp: timestamp, success: {
(ts) -> Void in
success?(ts: timestamp)
}) {(error) -> Void in
@@ -352,10 +411,10 @@ public class SlackWebAPI {
}
public func openIM(userID: String, success: ((imID: String?)->Void)?, failure: FailureClosure?) {
let parameters = ["user":userID]
client.api.request(.IMOpen, token: client.token, parameters: parameters, successClosure: {
let parameters: [String: Any] = ["user":userID]
client.api.request(endpoint: .IMOpen, token: client.token, parameters: parameters, successClosure: {
(response) -> Void in
let group = response["channel"] as? [String: AnyObject]
let group = response["channel"] as? [String: Any]
success?(imID: group?["id"] as? String)
}) {(error) -> Void in
failure?(error: error)
@@ -364,7 +423,7 @@ public class SlackWebAPI {
//MARK: - MPIM
public func closeMPIM(channel: String, success: ((closed: Bool)->Void)?, failure: FailureClosure?) {
close(.MPIMClose, channelID: channel, success: {
close(endpoint: .MPIMClose, channelID: channel, success: {
(closed) -> Void in
success?(closed: closed)
}) {(error) -> Void in
@@ -372,8 +431,8 @@ public class SlackWebAPI {
}
}
public func mpimHistory(id: String, latest: String = "\(NSDate().timeIntervalSince1970)", oldest: String = "0", inclusive: Bool = false, count: Int = 100, unreads: Bool = false, success: ((history: [String: AnyObject]?)->Void)?, failure: FailureClosure?) {
history(.MPIMHistory, id: id, latest: latest, oldest: oldest, inclusive: inclusive, count: count, unreads: unreads, success: {
public func mpimHistory(id: String, latest: String = "\(Time.slackTimestamp())", oldest: String = "0", inclusive: Bool = false, count: Int = 100, unreads: Bool = false, success: ((history: History?)->Void)?, failure: FailureClosure?) {
history(endpoint: .MPIMHistory, id: id, latest: latest, oldest: oldest, inclusive: inclusive, count: count, unreads: unreads, success: {
(history) -> Void in
success?(history: history)
}) {(error) -> Void in
@@ -381,8 +440,8 @@ public class SlackWebAPI {
}
}
public func mpimsList(excludeArchived: Bool = false, success: ((channels: [[String: AnyObject]]?)->Void)?, failure: FailureClosure?) {
list(.MPIMList, type:ChannelType.Group, excludeArchived: excludeArchived, success: {
public func mpimsList(excludeArchived: Bool = false, success: ((channels: [Any]?)->Void)?, failure: FailureClosure?) {
list(endpoint: .MPIMList, type:ChannelType.Group, excludeArchived: excludeArchived, success: {
(channels) -> Void in
success?(channels: channels)
}) {(error) -> Void in
@@ -391,7 +450,7 @@ public class SlackWebAPI {
}
public func markMPIM(channel: String, timestamp: String, success: ((ts: String)->Void)?, failure: FailureClosure?) {
mark(.MPIMMark, channel: channel, timestamp: timestamp, success: {
mark(endpoint: .MPIMMark, channel: channel, timestamp: timestamp, success: {
(ts) -> Void in
success?(ts: timestamp)
}) {(error) -> Void in
@@ -400,10 +459,10 @@ public class SlackWebAPI {
}
public func openMPIM(userIDs: [String], success: ((mpimID: String?)->Void)?, failure: FailureClosure?) {
let parameters = ["users":userIDs.joinWithSeparator(",")]
client.api.request(.MPIMOpen, token: client.token, parameters: parameters, successClosure: {
let parameters: [String: Any] = ["users":userIDs.joined(separator: ",")]
client.api.request(endpoint: .MPIMOpen, token: client.token, parameters: parameters, successClosure: {
(response) -> Void in
let group = response["group"] as? [String: AnyObject]
let group = response["group"] as? [String: Any]
success?(mpimID: group?["id"] as? String)
}) {(error) -> Void in
failure?(error: error)
@@ -412,7 +471,7 @@ public class SlackWebAPI {
//MARK: - Pins
public func pinItem(channel: String, file: String? = nil, fileComment: String? = nil, timestamp: String? = nil, success: ((pinned: Bool)->Void)?, failure: FailureClosure?) {
pin(.PinsAdd, channel: channel, file: file, fileComment: fileComment, timestamp: timestamp, success: {
pin(endpoint: .PinsAdd, channel: channel, file: file, fileComment: fileComment, timestamp: timestamp, success: {
(ok) -> Void in
success?(pinned: ok)
}) {(error) -> Void in
@@ -421,7 +480,7 @@ public class SlackWebAPI {
}
public func unpinItem(channel: String, file: String? = nil, fileComment: String? = nil, timestamp: String? = nil, success: ((unpinned: Bool)->Void)?, failure: FailureClosure?) {
pin(.PinsRemove, channel: channel, file: file, fileComment: fileComment, timestamp: timestamp, success: {
pin(endpoint: .PinsRemove, channel: channel, file: file, fileComment: fileComment, timestamp: timestamp, success: {
(ok) -> Void in
success?(unpinned: ok)
}) {(error) -> Void in
@@ -430,8 +489,8 @@ public class SlackWebAPI {
}
private func pin(endpoint: SlackAPIEndpoint, channel: String, file: String? = nil, fileComment: String? = nil, timestamp: String? = nil, success: ((ok: Bool)->Void)?, failure: FailureClosure?) {
let parameters: [String: AnyObject?] = ["channel":channel, "file":file, "file_comment":fileComment, "timestamp":timestamp]
client.api.request(endpoint, token: client.token, parameters: filterNilParameters(parameters), successClosure: {
let parameters: [String: Any?] = ["channel":channel, "file":file, "file_comment":fileComment, "timestamp":timestamp]
client.api.request(endpoint: endpoint, token: client.token, parameters: filterNilParameters(parameters: parameters), successClosure: {
(response) -> Void in
success?(ok: true)
}){(error) -> Void in
@@ -442,7 +501,7 @@ public class SlackWebAPI {
//MARK: - Reactions
// One of file, file_comment, or the combination of channel and timestamp must be specified.
public func addReaction(name: String, file: String? = nil, fileComment: String? = nil, channel: String? = nil, timestamp: String? = nil, success: ((reacted: Bool)->Void)?, failure: FailureClosure?) {
react(.ReactionsAdd, name: name, file: file, fileComment: fileComment, channel: channel, timestamp: timestamp, success: {
react(endpoint: .ReactionsAdd, name: name, file: file, fileComment: fileComment, channel: channel, timestamp: timestamp, success: {
(ok) -> Void in
success?(reacted: ok)
}) {(error) -> Void in
@@ -452,7 +511,7 @@ public class SlackWebAPI {
// One of file, file_comment, or the combination of channel and timestamp must be specified.
public func removeReaction(name: String, file: String? = nil, fileComment: String? = nil, channel: String? = nil, timestamp: String? = nil, success: ((unreacted: Bool)->Void)?, failure: FailureClosure?) {
react(.ReactionsRemove, name: name, file: file, fileComment: fileComment, channel: channel, timestamp: timestamp, success: {
react(endpoint: .ReactionsRemove, name: name, file: file, fileComment: fileComment, channel: channel, timestamp: timestamp, success: {
(ok) -> Void in
success?(unreacted: ok)
}) {(error) -> Void in
@@ -461,8 +520,8 @@ public class SlackWebAPI {
}
private func react(endpoint: SlackAPIEndpoint, name: String, file: String? = nil, fileComment: String? = nil, channel: String? = nil, timestamp: String? = nil, success: ((ok: Bool)->Void)?, failure: FailureClosure?) {
let parameters: [String: AnyObject?] = ["name":name, "file":file, "file_comment":fileComment, "channel":channel, "timestamp":timestamp]
client.api.request(endpoint, token: client.token, parameters: filterNilParameters(parameters), successClosure: {
let parameters: [String: Any?] = ["name":name, "file":file, "file_comment":fileComment, "channel":channel, "timestamp":timestamp]
client.api.request(endpoint: endpoint, token: client.token, parameters: filterNilParameters(parameters: parameters), successClosure: {
(response) -> Void in
success?(ok: true)
}) {(error) -> Void in
@@ -473,7 +532,7 @@ public class SlackWebAPI {
//MARK: - Stars
// One of file, file_comment, channel, or the combination of channel and timestamp must be specified.
public func addStar(file: String? = nil, fileComment: String? = nil, channel: String? = nil, timestamp: String? = nil, success: ((starred: Bool)->Void)?, failure: FailureClosure?) {
star(.StarsAdd, file: file, fileComment: fileComment, channel: channel, timestamp: timestamp, success: {
star(endpoint: .StarsAdd, file: file, fileComment: fileComment, channel: channel, timestamp: timestamp, success: {
(ok) -> Void in
success?(starred: ok)
}) {(error) -> Void in
@@ -483,7 +542,7 @@ public class SlackWebAPI {
// One of file, file_comment, channel, or the combination of channel and timestamp must be specified.
public func removeStar(file: String? = nil, fileComment: String? = nil, channel: String? = nil, timestamp: String? = nil, success: ((unstarred: Bool)->Void)?, failure: FailureClosure?) {
star(.StarsRemove, file: file, fileComment: fileComment, channel: channel, timestamp: timestamp, success: {
star(endpoint: .StarsRemove, file: file, fileComment: fileComment, channel: channel, timestamp: timestamp, success: {
(ok) -> Void in
success?(unstarred: ok)
}) {(error) -> Void in
@@ -492,8 +551,8 @@ public class SlackWebAPI {
}
private func star(endpoint: SlackAPIEndpoint, file: String?, fileComment: String?, channel: String?, timestamp: String?, success: ((ok: Bool)->Void)?, failure: FailureClosure?) {
let parameters: [String: AnyObject?] = ["file":file, "file_comment":fileComment, "channel":channel, "timestamp":timestamp]
client.api.request(endpoint, token: client.token, parameters: filterNilParameters(parameters), successClosure: {
let parameters: [String: Any?] = ["file":file, "file_comment":fileComment, "channel":channel, "timestamp":timestamp]
client.api.request(endpoint: endpoint, token: client.token, parameters: filterNilParameters(parameters: parameters), successClosure: {
(response) -> Void in
success?(ok: true)
}) {(error) -> Void in
@@ -503,10 +562,10 @@ public class SlackWebAPI {
//MARK: - Team
public func teamInfo(success: ((info: [String: AnyObject]?)->Void)?, failure: FailureClosure?) {
client.api.request(.TeamInfo, token: client.token, parameters: nil, successClosure: {
public func teamInfo(success: ((info: [String: Any]?)->Void)?, failure: FailureClosure?) {
client.api.request(endpoint: .TeamInfo, token: client.token, parameters: nil, successClosure: {
(response) -> Void in
success?(info: response["team"] as? [String: AnyObject])
success?(info: response["team"] as? [String: Any])
}) {(error) -> Void in
failure?(error: error)
}
@@ -514,8 +573,8 @@ public class SlackWebAPI {
//MARK: - Users
public func userPresence(user: String, success: ((presence: String?)->Void)?, failure: FailureClosure?) {
let parameters: [String: AnyObject] = ["user":user]
client.api.request(.UsersGetPresence, token: client.token, parameters: parameters, successClosure: {
let parameters: [String: Any] = ["user":user]
client.api.request(endpoint: .UsersGetPresence, token: client.token, parameters: parameters, successClosure: {
(response) -> Void in
success?(presence: response["presence"] as? String)
}){(error) -> Void in
@@ -524,27 +583,27 @@ public class SlackWebAPI {
}
public func userInfo(id: String, success: ((user: User?)->Void)?, failure: FailureClosure?) {
let parameters: [String: AnyObject] = ["user":id]
client.api.request(.UsersInfo, token: client.token, parameters: parameters, successClosure: {
let parameters: [String: Any] = ["user":id]
client.api.request(endpoint: .UsersInfo, token: client.token, parameters: parameters, successClosure: {
(response) -> Void in
success?(user: User(user: response["user"] as? [String: AnyObject]))
success?(user: User(user: response["user"] as? [String: Any]))
}) {(error) -> Void in
failure?(error: error)
}
}
public func usersList(includePresence: Bool = false, success: ((userList: [[String: AnyObject]]?)->Void)?, failure: FailureClosure?) {
let parameters: [String: AnyObject] = ["presence":includePresence]
client.api.request(.UsersList, token: client.token, parameters: parameters, successClosure: {
public func usersList(includePresence: Bool = false, success: ((userList: [String: Any]?)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any] = ["presence":includePresence]
client.api.request(endpoint: .UsersList, token: client.token, parameters: parameters, successClosure: {
(response) -> Void in
success?(userList: response["members"] as? [[String: AnyObject]])
success?(userList: response["members"] as? [String: Any])
}){(error) -> Void in
failure?(error: error)
}
}
public func setUserActive(success: ((success: Bool)->Void)?, failure: FailureClosure?) {
client.api.request(.UsersSetActive, token: client.token, parameters: nil, successClosure: {
client.api.request(endpoint: .UsersSetActive, token: client.token, parameters: nil, successClosure: {
(response) -> Void in
success?(success: true)
}) {(error) -> Void in
@@ -553,8 +612,8 @@ public class SlackWebAPI {
}
public func setUserPresence(presence: Presence, success: ((success: Bool)->Void)?, failure: FailureClosure?) {
let parameters: [String: AnyObject] = ["presence":presence.rawValue]
client.api.request(.UsersSetPresence, token: client.token, parameters: parameters, successClosure: {
let parameters: [String: Any] = ["presence":presence.rawValue]
client.api.request(endpoint: .UsersSetPresence, token: client.token, parameters: parameters, successClosure: {
(response) -> Void in
success?(success:true)
}) {(error) -> Void in
@@ -564,8 +623,8 @@ public class SlackWebAPI {
//MARK: - Channel Utilities
private func close(endpoint: SlackAPIEndpoint, channelID: String, success: ((closed: Bool)->Void)?, failure: FailureClosure?) {
let parameters: [String: AnyObject] = ["channel":channelID]
client.api.request(endpoint, token: client.token, parameters: parameters, successClosure: {
let parameters: [String: Any] = ["channel":channelID]
client.api.request(endpoint: endpoint, token: client.token, parameters: parameters, successClosure: {
(response) -> Void in
success?(closed: true)
}) {(error) -> Void in
@@ -573,39 +632,39 @@ public class SlackWebAPI {
}
}
private func history(endpoint: SlackAPIEndpoint, id: String, latest: String = "\(NSDate().timeIntervalSince1970)", oldest: String = "0", inclusive: Bool = false, count: Int = 100, unreads: Bool = false, success: ((history: [String: AnyObject]?)->Void)?, failure: FailureClosure?) {
let parameters: [String: AnyObject] = ["channel": id, "latest": latest, "oldest": oldest, "inclusive":inclusive, "count":count, "unreads":unreads]
client.api.request(endpoint, token: client.token, parameters: parameters, successClosure: {
private func history(endpoint: SlackAPIEndpoint, id: String, latest: String = "\(Time.slackTimestamp())", oldest: String = "0", inclusive: Bool = false, count: Int = 100, unreads: Bool = false, success: ((history: History?)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any] = ["channel": id, "latest": latest, "oldest": oldest, "inclusive":inclusive, "count":count, "unreads":unreads]
client.api.request(endpoint: endpoint, token: client.token, parameters: parameters, successClosure: {
(response) -> Void in
success?(history: response)
success?(history: History(history: response))
}) {(error) -> Void in
failure?(error: error)
}
}
private func info(endpoint: SlackAPIEndpoint, type: ChannelType, id: String, success: ((channel: Channel?)->Void)?, failure: FailureClosure?) {
let parameters: [String: AnyObject] = ["channel": id]
client.api.request(endpoint, token: client.token, parameters: parameters, successClosure: {
let parameters: [String: Any] = ["channel": id]
client.api.request(endpoint: endpoint, token: client.token, parameters: parameters, successClosure: {
(response) -> Void in
success?(channel: Channel(channel: response[type.rawValue] as? [String: AnyObject]))
success?(channel: Channel(channel: response[type.rawValue] as? [String: Any]))
}) {(error) -> Void in
failure?(error: error)
}
}
private func list(endpoint: SlackAPIEndpoint, type: ChannelType, excludeArchived: Bool = false, success: ((channels: [[String: AnyObject]]?)->Void)?, failure: FailureClosure?) {
let parameters: [String: AnyObject] = ["exclude_archived": excludeArchived]
client.api.request(endpoint, token: client.token, parameters: parameters, successClosure: {
private func list(endpoint: SlackAPIEndpoint, type: ChannelType, excludeArchived: Bool = false, success: ((channels: [Any]?)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any] = ["exclude_archived": excludeArchived]
client.api.request(endpoint: endpoint, token: client.token, parameters: parameters, successClosure: {
(response) -> Void in
success?(channels: response[type.rawValue+"s"] as? [[String: AnyObject]])
success?(channels: response[type.rawValue+"s"] as? [Any])
}) {(error) -> Void in
failure?(error: error)
}
}
private func mark(endpoint: SlackAPIEndpoint, channel: String, timestamp: String, success: ((ts: String)->Void)?, failure: FailureClosure?) {
let parameters: [String: AnyObject] = ["channel": channel, "ts": timestamp]
client.api.request(endpoint, token: client.token, parameters: parameters, successClosure: {
let parameters: [String: Any] = ["channel": channel, "ts": timestamp]
client.api.request(endpoint: endpoint, token: client.token, parameters: parameters, successClosure: {
(response) -> Void in
success?(ts: timestamp)
}) {(error) -> Void in
@@ -614,8 +673,8 @@ public class SlackWebAPI {
}
private func setInfo(endpoint: SlackAPIEndpoint, type: InfoType, channel: String, text: String, success: ((success: Bool)->Void)?, failure: FailureClosure?) {
let parameters: [String: AnyObject] = ["channel": channel, type.rawValue: text]
client.api.request(endpoint, token: client.token, parameters: parameters, successClosure: {
let parameters: [String: Any] = ["channel": channel, type.rawValue: text]
client.api.request(endpoint: endpoint, token: client.token, parameters: parameters, successClosure: {
(response) -> Void in
success?(success: true)
}) {(error) -> Void in
@@ -624,8 +683,8 @@ public class SlackWebAPI {
}
//MARK: - Filter Nil Parameters
private func filterNilParameters(parameters: [String: AnyObject?]) -> [String: AnyObject] {
var finalParameters = [String: AnyObject]()
private func filterNilParameters(parameters: [String: Any?]) -> [String: Any] {
var finalParameters = [String: Any]()
for key in parameters.keys {
if parameters[key] != nil {
finalParameters[key] = parameters[key]!
@@ -633,4 +692,35 @@ public class SlackWebAPI {
}
return finalParameters
}
//MARK: - Encode Attachments
private func encodeAttachments(attachments: [Attachment?]?) -> String? {
if let attachments = attachments {
var attachmentArray: [[String: Any]] = []
for attachment in attachments {
if let attachment = attachment {
attachmentArray.append(attachment.dictionary())
}
}
do {
let string = try Jay().dataFromJson(attachmentArray).string()
return string
} catch _ {
}
}
return nil
}
//MARK: - Enumerate Do Not Distrub Status
private func enumerateDNDStauses(statuses: [String: Any]?) -> [String: DoNotDisturbStatus] {
var retVal = [String: DoNotDisturbStatus]()
if let keys = statuses?.keys {
for key in keys {
retVal[key] = DoNotDisturbStatus(status: statuses?[key] as? [String: Any])
}
}
return retVal
}
}
@@ -21,9 +21,7 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public enum SlackError: ErrorType {
public enum SlackError: ErrorProtocol {
case AccountInactive
case AlreadyArchived
case AlreadyInChannel
@@ -34,6 +32,7 @@ public enum SlackError: ErrorType {
case BadRedirectURI
case BadTimeStamp
case CantArchiveGeneral
case CantDelete
case CantDeleteFile
case CantDeleteMessage
case CantInvite
@@ -75,6 +74,7 @@ public enum SlackError: ErrorType {
case MissingPostType
case NameTaken
case NoChannel
case NoComment
case NoItemSpecified
case NoReaction
case NoText
@@ -131,6 +131,8 @@ internal struct ErrorDispatcher {
return .BadRedirectURI
case "bad_timestamp":
return .BadTimeStamp
case "cant_delete":
return .CantDelete
case "cant_delete_file":
return .CantDeleteFile
case "cant_delete_message":
@@ -213,6 +215,8 @@ internal struct ErrorDispatcher {
return .NameTaken
case "no_channel":
return .NoChannel
case "no_comment":
return .NoComment
case "no_reaction":
return .NoReaction
case "no_item_specified":
+32 -7
View File
@@ -25,21 +25,46 @@ public struct Team {
public let id: String
internal(set) public var name: String?
internal(set) public var emailDomain: String?
internal(set) public var domain: String?
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?["id"] as? String
emailDomain = team?["email_domain"] as? String
name = team?["name"] as? String
domain = team?["domain"] as? String
messageEditWindowMinutes = team?["mesg_edit_window_mins"] as? Int
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: Any])
}
}
public struct TeamIcon {
internal(set) public var image34: String?
internal(set) public var image44: String?
internal(set) public var image68: String?
internal(set) public var image88: String?
internal(set) public var image102: String?
internal(set) public var image132: String?
internal(set) public var imageOriginal: String?
internal(set) public var imageDefault: Bool?
internal init?(icon: [String: Any]?) {
image34 = icon?["image_34"] as? String
image44 = icon?["image_44"] as? String
image68 = icon?["image_68"] as? String
image88 = icon?["image_88"] as? String
image102 = icon?["image_102"] as? String
image132 = icon?["image_132"] as? String
imageOriginal = icon?["image_original"] as? String
imageDefault = icon?["image_default"] as? Bool
}
}
+107 -12
View File
@@ -21,23 +21,45 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// MARK: - Edited
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
}
}
// MARK: - History
public struct History {
internal(set) public var latest: Double?
internal(set) public var messages = [Message]()
public let hasMore: Bool?
internal init?(history: [String: Any]?) {
if let latestStr = history?["latest"] as? String, latestDouble = Double(latestStr) {
latest = latestDouble
}
if let msgs = history?["messages"] as? [Any] {
for message in msgs {
if let message = Message(message: message as? [String: Any]) {
messages.append(message)
}
}
}
hasMore = history?["has_more"] as? Bool
}
}
// MARK: - Reaction
public struct Reaction {
public let name: String?
internal(set) public var users = [String: String]()
internal init?(reaction:[String: AnyObject]?) {
internal init?(reaction:[String: Any]?) {
name = reaction?["name"] as? String
}
@@ -51,7 +73,7 @@ public struct Reaction {
self.users = users
}
static func reactionsFromArray(array: [[String: AnyObject]]) -> [String: Reaction] {
static func reactionsFromArray(array: [[String: Any]]) -> [String: Reaction] {
var reactions = [String: Reaction]()
var userDictionary = [String: String]()
for reaction in array {
@@ -85,7 +107,7 @@ public struct Comment {
internal(set) public var stars: Int?
internal(set) public var reactions = [String: 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
@@ -116,23 +138,23 @@ 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(message: item?["message"] as? [String: Any])
// Comment and File can come across as Strings or Dictionaries
if (Comment(comment: item?["comment"] as? [String: AnyObject])?.id == nil) {
if (Comment(comment: item?["comment"] as? [String: Any])?.id == nil) {
comment = Comment(id: item?["comment"] as? String)
} else {
comment = Comment(comment: item?["comment"] as? [String: AnyObject])
comment = Comment(comment: item?["comment"] as? [String: Any])
}
if (File(file: item?["file"] as? [String: AnyObject])?.id == nil) {
if (File(file: item?["file"] as? [String: Any])?.id == nil) {
file = File(id: item?["file"] as? String)
} else {
file = File(file: item?["file"] as? [String: AnyObject])
file = File(file: item?["file"] as? [String: Any])
}
fileCommentID = item?["file_comment"] as? String
@@ -151,7 +173,7 @@ public struct Topic {
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
@@ -166,7 +188,7 @@ public struct DoNotDisturbStatus {
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
@@ -175,3 +197,76 @@ public struct DoNotDisturbStatus {
}
}
// MARK - Custom Team Profile
public struct CustomProfile {
internal(set) public var fields = [String: CustomProfileField]()
internal init?(profile: [String: Any]?) {
if let eventFields = profile?["fields"] as? [Any] {
for field in eventFields {
if let cpf = CustomProfileField(field: field as? [String: Any]), id = cpf.id {
fields[id] = cpf
} else {
if let cpf = CustomProfileField(id: field as? String), id = cpf.id {
fields[id] = cpf
}
}
}
}
}
internal init?(customFields: [String: Any]?) {
if let customFields = customFields {
for key in customFields.keys {
if let cpf = CustomProfileField(field: customFields[key] as? [String: Any]) {
self.fields[key] = cpf
}
}
}
}
}
public struct CustomProfileField {
internal(set) public var id: String?
internal(set) public var alt: String?
internal(set) public var value: String?
internal(set) public var hidden: Bool?
internal(set) public var hint: String?
internal(set) public var label: String?
internal(set) public var options: String?
internal(set) public var ordering: Int?
internal(set) public var possibleValues: [String]?
internal(set) public var type: String?
internal init?(field: [String: Any]?) {
id = field?["id"] as? String
alt = field?["alt"] as? String
value = field?["value"] as? String
hidden = field?["is_hidden"] as? Bool
hint = field?["hint"] as? String
label = field?["label"] as? String
options = field?["options"] as? String
ordering = field?["ordering"] as? Int
possibleValues = field?["possible_values"] as? [String]
type = field?["type"] as? String
}
internal init?(id: String?) {
self.id = id
}
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
hidden = profile?.hidden != nil ? profile?.hidden : hidden
hint = profile?.hint != nil ? profile?.hint : hint
label = profile?.label != nil ? profile?.label : label
options = profile?.options != nil ? profile?.options : options
ordering = profile?.ordering != nil ? profile?.ordering : ordering
possibleValues = profile?.possibleValues != nil ? profile?.possibleValues : possibleValues
type = profile?.type != nil ? profile?.type : type
}
}
+8 -5
View File
@@ -35,8 +35,9 @@ public struct User {
internal(set) public var image48: String?
internal(set) public var image72: String?
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
@@ -48,9 +49,11 @@ 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: Any])
}
}
public let id: String?
internal(set) public var name: String?
internal(set) public var deleted: Bool?
@@ -70,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
@@ -93,7 +96,7 @@ 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?) {
+3 -3
View File
@@ -39,11 +39,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
@@ -58,7 +58,7 @@ 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)