Compare commits

..

98 Commits

Author SHA1 Message Date
Peter Zignego c2f3731a69 Swift 4 2018-02-18 22:46:32 -05:00
Peter Zignego 48f80cc13d Merge pull request #121 from emorydunn/multispace
Multiple Workspace Support
2018-01-23 18:10:17 -05:00
Emory Dunn 0396d9c6d5 Add ClientConnection to Xcode 2018-01-22 14:44:46 -08:00
Emory Dunn 3514b637c8 Preserve compatibility with previous version
Add computed properties for `rtm` and `webAPI` that return the first client’s connections.
2017-12-28 22:45:10 -08:00
Emory Dunn 78ce839cc1 Move ClientConnection class to its own file 2017-12-28 22:36:38 -08:00
Emory Dunn 831bb20ff7 Add multiple client support
Add a new `ClientConnection` class to hold each client’s `Client`, RTM, and WebAPI connections.
2017-12-28 22:20:37 -08:00
Peter Zignego 43dda4a2f0 Update README.md 2017-07-14 16:51:39 -04:00
Peter Zignego 2f0978ccc4 majorVersion 4 2017-07-14 16:47:06 -04:00
Peter Zignego 71c5eda4a1 SwiftLint + gardening 2017-06-09 16:45:22 -04:00
Peter Zignego 4b241374ea Update README.md 2017-06-04 14:22:02 -04:00
Peter Zignego dd07b545c7 Merge branch '4.0'
# Conflicts:
#	Cartfile
#	Package.swift
#	Podfile
#	README.md
#	SlackKit.podspec
#	SlackKit.xcodeproj/project.pbxproj
#	Sources/SlackKit/Model/Message.swift
#	Sources/SlackKit/Model/User.swift
#	Sources/SlackKit/NetworkInterface.swift
#	Sources/SlackKit/WebAPI.swift
#	Supporting Files/Info.plist
2017-06-04 13:16:25 -04:00
Peter Zignego af4ba6623c Carthage support 2017-06-04 13:12:24 -04:00
Peter Zignego 435607d170 Update SlackKit.swift 2017-06-03 22:18:00 -04:00
Peter Zignego 8094bd2c6c Update .swift-version 2017-06-03 18:02:35 -04:00
Peter Zignego d8d22f6083 Update .swift-version 2017-06-03 18:02:24 -04:00
Peter Zignego 6fcfe2fda4 Update README.md 2017-06-02 23:08:38 -04:00
Peter Zignego 6ccce1875b Merge branch '4.0' of https://github.com/SlackKit/SlackKit into 4.0 2017-06-02 15:35:16 -04:00
Peter Zignego 433fc1a8ff Add platform 2017-06-02 15:34:58 -04:00
Peter Zignego 4f64c952b8 Update README.md 2017-06-02 15:26:08 -04:00
Peter Zignego 139b25a7f0 Add SKServer 2017-06-02 15:25:46 -04:00
Peter Zignego 3ee4e0fd1d Update README.md 2017-05-26 13:28:23 -04:00
Peter Zignego f013840cae SlackKit v4 2017-04-15 15:33:06 -04:00
Peter Zignego 79457aa13d Merge pull request #90 from skagedal/master
Add support for status text and status emoji
2017-04-15 10:27:34 -04:00
Simon Kågedal Reimer ac2657b7e1 Add support for status text and status emoji 2017-04-14 21:02:54 +02:00
Peter Zignego 82130f2e67 Merge pull request #89 from johntmcintosh/threads
Add support for the `thread_ts` parameter used to indicate and track threaded conversations
2017-04-11 21:41:46 -04:00
John McIntosh b9573c4e8b Add support for the thread_ts parameter used to indicate and track threaded conversations 2017-04-11 09:57:39 -05:00
Peter Zignego 6481620e7a Bump podspec 2017-04-09 17:16:46 -04:00
Peter Zignego 35e7ead8d1 Merge branch 'master' of https://github.com/pvzig/SlackKit 2017-04-09 17:14:46 -04:00
Peter Zignego 0f896fdaee xcodeproj gardening 2017-04-09 17:14:36 -04:00
Peter Zignego 8a4fceaa00 Swift 3.1 gardening 2017-04-09 17:12:08 -04:00
Peter Zignego 6007f790db Update README.md 2017-04-09 17:10:53 -04:00
Peter Zignego 05e7f2baa3 Merge pull request #88 from Xiangxin/swift3.1
Swift 3.1 initial update
2017-04-09 16:51:31 -04:00
Xiangxin 39871172e9 Adapt swift 3.1 changes and fix warnings 2017-03-30 14:50:26 +08:00
Peter Zignego 491f80741b Update podspec 2017-03-19 19:32:39 -04:00
Peter Zignego 0eb9ea31e1 3.1.11 2017-03-19 19:11:16 -04:00
Peter Zignego 8865376c3c Merge branch 'master' of https://github.com/pvzig/SlackKit 2017-03-18 15:21:42 -04:00
Peter Zignego d86d0108ff Update podfile 2017-03-18 15:21:01 -04:00
Peter Zignego b45b7085ce Update Package.swift 2017-03-18 15:17:30 -04:00
Peter Zignego 91193c6b2e Update podspec 2017-03-18 14:07:58 -04:00
Peter Zignego 9720b1c05c Merge branch 'master' of https://github.com/pvzig/SlackKit 2017-03-18 12:20:55 -04:00
Peter Zignego 9766a5ad6c Bump version strings 2017-03-18 12:20:48 -04:00
Peter Zignego 1e181e7580 Update README.md 2017-03-18 12:07:10 -04:00
Peter Zignego f6d6c779ae Update dependencies 2017-03-18 11:14:56 -04:00
Peter Zignego 11bb50f8d2 Delete Podfile.lock 2017-03-13 11:56:05 -04:00
Peter Zignego d721e0ba1a Delete Cartfile.resolved 2017-03-13 11:55:54 -04:00
Peter Zignego ba6066875c Update Package.swift 2017-03-13 11:55:40 -04:00
Peter Zignego 0f1a1a9de5 Update Cartfile 2017-03-13 11:54:43 -04:00
Peter Zignego a81cebf5c8 Update Podfile 2017-03-13 11:54:05 -04:00
Peter Zignego 007ec7ab69 License headers 2017-03-10 19:35:29 -05:00
Peter Zignego b93d411f63 More precise os preprocessor 2017-03-10 18:39:25 -05:00
Peter Zignego 741a23809d Additional linux fixes 2017-03-10 18:32:24 -05:00
Peter Zignego a92fd36c17 Additional fixes for linux 2017-03-10 18:29:19 -05:00
Peter Zignego e122610c04 Linux compilation fixes 2017-03-10 18:19:30 -05:00
Peter Zignego 0539e0bac2 Update .swift-version 2017-03-10 17:32:14 -05:00
Peter Zignego 3416161818 Clean up 2017-03-10 17:29:43 -05:00
Peter Zignego 32a4aa13ea Clean up 2017-03-10 17:28:22 -05:00
Peter Zignego cf188ffb6a Gardening 2017-03-10 17:28:06 -05:00
Peter Zignego f1a1963ac8 Acess control 2017-03-10 17:27:51 -05:00
Peter Zignego 645797b72e Add OAuth config 2017-03-09 19:25:09 -05:00
Peter Zignego b9f808f70e Rename ClientOptions to RTMOptions 2017-03-09 19:24:51 -05:00
Peter Zignego 74ef3979f5 Renaming 2017-03-07 18:16:21 -05:00
Peter Zignego 992879f54f Update copyright year 2017-03-07 01:41:38 -05:00
Peter Zignego ccdf9d5d3c SKServer 2017-03-07 01:29:27 -05:00
Peter Zignego 0336b5a9b6 Synchronous request 2017-03-07 01:28:59 -05:00
Peter Zignego aefbeafd28 Break out WebAPI 2017-03-06 20:29:50 -05:00
Peter Zignego bc6c07f045 Update SKCore 2017-03-06 20:28:13 -05:00
Peter Zignego db24e66d33 Postpone events 2017-02-22 22:12:34 -05:00
Peter Zignego ef70f935c1 Renaming… 2017-02-22 22:12:16 -05:00
Peter Zignego afbf8ab6fe Naming… 2017-02-22 21:42:43 -05:00
Peter Zignego d39296f496 SKServer initial 2017-02-22 21:13:07 -05:00
Peter Zignego eafceb4645 Split Client from RTM 2017-02-22 19:54:07 -05:00
Peter Zignego 83cf85a27a SKCommon -> SKCore 2017-02-22 19:53:13 -05:00
Peter Zignego 06e250a954 RTM clean up 2017-02-21 23:10:13 -05:00
Peter Zignego 5b6622a961 v4 WIP 2017-02-20 13:10:45 -05:00
Peter Zignego a58e291d2e Organization 2017-02-04 18:21:37 -05:00
Peter Zignego a0e1f9844e Access control, organization 2017-02-04 13:32:26 -05:00
Peter Zignego 7d524ddeac Split to Common, Client, Server 2017-02-04 12:48:03 -05:00
Peter Zignego 94c9f7fe5a Bump version 2017-01-25 12:31:34 -05:00
Peter Zignego be8a5879f3 Merge pull request #77 from norwoodsystems/master
Updated podspec
2017-01-25 12:29:03 -05:00
kiancheong c657919704 Updated podspec 2017-01-25 14:42:19 +08:00
Peter Zignego abeef21d7a Merge pull request #75 from sersoft-gmbh/master
Fix author_name in Attachment, add Markdown fields for Attachments, fix optionality
2017-01-21 10:53:28 -05:00
Florian Friedrich 79e3b14593 Add missing ? in AttachmentField initializer 2017-01-20 16:16:35 +01:00
Florian Friedrich d9a4cda9b0 Made AttachmentField init params optional, fix author_name key in Attachment, add markdown fields to attachment 2017-01-20 16:11:08 +01:00
Peter Zignego 12b316da0b Merge pull request #73 from strogonoff/patch-1
OAuth: scopes must be supplied
2017-01-18 09:20:53 -05:00
Anton Strogonoff 13cade5c00 OAuth: scopes must be supplied
Slack API spec requires the "scope" parameter when requesting authorization code. Without it a token cannot be obtained as request fails with an error.
2017-01-18 16:21:03 +07:00
Peter Zignego 051e8dd6c8 Fix podspec 2017-01-16 22:11:52 -05:00
Peter Zignego 1adea1c54e Fix podspec 2017-01-16 22:02:43 -05:00
Peter Zignego aa51cfb2fd Version bump 2017-01-16 21:37:49 -05:00
Peter Zignego 6b8885bd29 Merge pull request #72 from pvzig/3.1.8
3.1.8
2017-01-16 21:34:58 -05:00
Peter Zignego e0fbf1ab4e Add logging of unsupported events 2017-01-16 21:32:21 -05:00
Peter Zignego 366c6e7b77 Merge pull request #68 from pvzig/master-project-structure
Project organization
2017-01-06 17:59:37 -05:00
Peter Zignego 378c116d9b Project organization 2017-01-06 17:42:06 -05:00
Peter Zignego 58bade8ec9 Bump version 2017-01-04 22:10:18 -05:00
Peter Zignego 7d7f5c40d6 Update readme 2017-01-04 22:09:18 -05:00
Peter Zignego c9fd54d106 Merge pull request #66 from pvzig/3.1.7
3.1.7
2017-01-04 22:08:10 -05:00
Peter Zignego 2f1ce799ad URLComponents and WebAPI clean up 2017-01-04 22:06:47 -05:00
Peter Zignego 7f02f4cf99 Update readme 2017-01-03 22:07:57 -05:00
Peter Zignego a9066c0d0a Bump version 2017-01-03 21:29:49 -05:00
66 changed files with 705 additions and 5652 deletions
+1 -1
View File
@@ -1 +1 @@
3.0
4.0
+7
View File
@@ -0,0 +1,7 @@
disabled_rules:
- identifier_name
- function_parameter_count
line_length: 140
excluded: # paths to ignore during linting. Takes precedence over `included`.
- Carthage
- Pods
+4 -2
View File
@@ -1,2 +1,4 @@
github "https://github.com/daltoniam/Starscream" == 2.0.2
github "https://github.com/pvzig/swifter.git" == 3.0.4
github "SlackKit/SKCore" >= 4.1.0
github "SlackKit/SKClient" >= 4.1.0
github "SlackKit/SKRTMAPI" >= 4.1.0
github "SlackKit/SKServer" >= 4.1.0
-2
View File
@@ -1,2 +0,0 @@
github "daltoniam/Starscream" "2.0.2"
github "pvzig/swifter" "3.0.4"
+1 -1
View File
@@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) 2016 Peter Zignego
Copyright (c) 2017 Peter Zignego
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+13 -4
View File
@@ -1,11 +1,20 @@
// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "SlackKit",
targets: [],
products: [
.library(name: "SlackKit", targets: ["SlackKit"])
],
dependencies: [
.Package(url: "https://github.com/pvzig/swifter.git",
majorVersion: 3, minor: 0),
.Package(url: "https://github.com/daltoniam/Starscream", majorVersion: 2, minor: 0)
.package(url: "https://github.com/SlackKit/SKCore", .upToNextMinor(from: "4.1.0")),
.package(url: "https://github.com/SlackKit/SKClient", .upToNextMinor(from: "4.1.0")),
.package(url: "https://github.com/SlackKit/SKRTMAPI", .upToNextMinor(from: "4.1.0")),
.package(url: "https://github.com/SlackKit/SKServer", .upToNextMinor(from: "4.1.0"))
],
targets: [
.target(name: "SlackKit",
dependencies: ["SKCore", "SKClient", "SKRTMAPI", "SKServer"],
path: "Sources")
]
)
+19 -9
View File
@@ -1,18 +1,28 @@
source 'https://github.com/CocoaPods/Specs.git'
use_frameworks!
target 'SlackKit OS X' do
pod 'Starscream', '~> 2.0.2'
pod 'Swifter', :git => 'https://github.com/pvzig/swifter.git', :tag => '3.0.4'
target 'SlackKit macOS' do
platform :osx, '10.11'
pod 'SKCore', '~> 4.1.0'
pod 'SKClient', '~> 4.1.0'
pod 'SKWebAPI', '~> 4.1.0'
pod 'SKRTMAPI', '~> 4.1.0'
pod 'SKServer', '~> 4.1.0'
end
target 'SlackKit iOS' do
pod 'Starscream', '~> 2.0.2'
pod 'Swifter', :git => 'https://github.com/pvzig/swifter.git', :tag => '3.0.4'
platform :ios, '9.0'
pod 'SKCore', '~> 4.1.0'
pod 'SKClient', '~> 4.1.0'
pod 'SKWebAPI', '~> 4.1.0'
pod 'SKRTMAPI', '~> 4.1.0'
pod 'SKServer', '~> 4.1.0'
end
target 'SlackKit tvOS' do
pod 'Starscream', '~> 2.0.2'
pod 'Swifter', :git => 'https://github.com/pvzig/swifter.git', :tag => '3.0.4'
platform :tvos, '9.0'
pod 'SKCore', '~> 4.1.0'
pod 'SKClient', '~> 4.1.0'
pod 'SKWebAPI', '~> 4.1.0'
pod 'SKRTMAPI', '~> 4.1.0'
pod 'SKServer', '~> 4.1.0'
end
-25
View File
@@ -1,25 +0,0 @@
PODS:
- Starscream (2.0.2)
- Swifter (1.3.2)
DEPENDENCIES:
- Starscream (~> 2.0.2)
- Swifter (from `https://github.com/pvzig/swifter.git`, tag `3.0.4`)
EXTERNAL SOURCES:
Swifter:
:git: https://github.com/pvzig/swifter.git
:tag: 3.0.4
CHECKOUT OPTIONS:
Swifter:
:git: https://github.com/pvzig/swifter.git
:tag: 3.0.4
SPEC CHECKSUMS:
Starscream: 6c135a34e0a6e60cedaa0b30db67a4c05cf7cd38
Swifter: dd1800ba8eb3e28b22b8bd20f91a8561a0110fac
PODFILE CHECKSUM: cd86ea0f8422027c9d5fa3c40243ae7a816fb79a
COCOAPODS: 1.1.0.rc.3
+167 -277
View File
@@ -1,317 +1,207 @@
![SlackKit](https://cloud.githubusercontent.com/assets/8311605/10260893/5ec60f96-694e-11e5-91fd-da6845942201.png)
<p align="center"><img src="https://cloud.githubusercontent.com/assets/8311605/24083714/e921a0d4-0cb2-11e7-8384-d42113ef5056.png" alt="SlackKit" width="500"/></p>
![Swift Version](https://img.shields.io/badge/Swift-3.0-orange.svg) ![Plaforms](https://img.shields.io/badge/Platforms-macOS,iOS,tvOS-lightgrey.svg) ![License MIT](https://img.shields.io/badge/License-MIT-lightgrey.svg) [![CocoaPods compatible](https://img.shields.io/badge/CocoaPods-compatible-brightgreen.svg)](https://cocoapods.org) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-brightgreen.svg)](https://github.com/Carthage/Carthage) [![SwiftPM compatible](https://img.shields.io/badge/SwiftPM-compatible-brightgreen.svg)](https://github.com/apple/swift-package-manager)
## SlackKit: A Swift Slack Client Library
![Swift Version](https://img.shields.io/badge/Swift-4.0.3-orange.svg)
![Plaforms](https://img.shields.io/badge/Platforms-macOS,iOS,tvOS,Linux-lightgrey.svg)
![License MIT](https://img.shields.io/badge/License-MIT-lightgrey.svg)
[![SwiftPM compatible](https://img.shields.io/badge/SwiftPM-compatible-brightgreen.svg)](https://github.com/apple/swift-package-manager)
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-brightgreen.svg)](https://github.com/Carthage/Carthage)
[![CocoaPods compatible](https://img.shields.io/badge/CocoaPods-compatible-brightgreen.svg)](https://cocoapods.org)
## SlackKit: Slack Apps in Swift
### Description
This is a Slack client library for OS X, iOS, and tvOS written in Swift. It's intended to expose all of the functionality of Slack's [Real Time Messaging API](https://api.slack.com/rtm) as well as the [web APIs](https://api.slack.com/web) that are accessible to [bot users](https://api.slack.com/bot-users). SlackKit also supports Slacks [OAuth 2.0](https://api.slack.com/docs/oauth) flow including the [Add to Slack](https://api.slack.com/docs/slack-button) and [Sign in with Slack](https://api.slack.com/docs/sign-in-with-slack) buttons, [incoming webhooks](https://api.slack.com/incoming-webhooks), [slash commands](https://api.slack.com/slash-commands), and [message buttons](https://api.slack.com/docs/message-buttons).
SlackKit makes it easy to build Slack apps in Swift.
This is the **Swift 3** branch of SlackKit. SlackKit also has support for [Swift 2.3](https://github.com/pvzig/SlackKit/tree/swift2.3) and [Linux](https://github.com/pvzig/SlackKit/tree/linux).
#### Building the SlackKit Framework
To build the SlackKit project directly, first build the dependencies using Carthage or CocoaPods. To use the framework in your application, install it in one of the following ways:
It's intended to expose all of the functionality of Slack's [Real Time Messaging API](https://api.slack.com/rtm) as well as the [web APIs](https://api.slack.com/web) that are accessible to [bot users](https://api.slack.com/bot-users). SlackKit also supports Slacks [OAuth 2.0](https://api.slack.com/docs/oauth) flow including the [Add to Slack](https://api.slack.com/docs/slack-button) and [Sign in with Slack](https://api.slack.com/docs/sign-in-with-slack) buttons, [incoming webhooks](https://api.slack.com/incoming-webhooks), [slash commands](https://api.slack.com/slash-commands), and [message buttons](https://api.slack.com/docs/message-buttons).
### Installation
#### CocoaPods
Add SlackKit to your pod file:
```
use_frameworks!
pod 'SlackKit', '~> 3.1.5'
```
and run
```
# Use CocoaPods version >= 1.1.0
pod install
```
#### Carthage
Add SlackKit to your Cartfile:
```
github "https://github.com/pvzig/slackkit.git"
```
and run
```
carthage bootstrap
```
**Note:** If youre seeing long compile times with optimizations turned on, try updating to the latest version of Xcode, 8.2.1.
Drag the built `SlackKit.framework` into your Xcode project.
#### Swift Package Manager
Add SlackKit to your Package.swift
Add `SlackKit` to your `Package.swift`
```swift
import PackageDescription
let package = Package(
dependencies: [
.Package(url: "https://github.com/pvzig/SlackKit.git", majorVersion: 3)
.package(url: "https://github.com/SlackKit/SlackKit.git", .upToNextMinor(from: "4.1.0"))
]
)
```
Run `swift build` on your applications main directory.
#### Carthage
Add `SlackKit` to your `Cartfile`:
To use the library in your project import it:
```
import SlackKit
github "SlackKit/SlackKit"
```
#### CocoaPods
Add `SlackKit` to your `Podfile`:
```
pod 'SlackKit'
```
### Usage
#### The Basics
Create a bot user with an API token:
```swift
import SlackKit
let bot = SlackKit()
bot.addRTMBotWithAPIToken("xoxb-SLACK-BOT-TOKEN")
// Register for event notifications
bot.notificationForEvent(.message) { (event, _) in
// Your bot logic here
print(event.message)
}
```
or create a ready-to-launch Slack app with your [applications `Client ID` and `Client Secret`](https://api.slack.com/apps):
```swift
import SlackKit
let bot = SlackKit()
let oauthConfig = OAuthConfig(clientID: "CLIENT_ID", clientSecret: "CLIENT_SECRET")
bot.addServer(oauth: oauthConfig)
```
or just make calls to the Slack Web API:
```swift
import SlackKit
let bot = SlackKit()
bot.addWebAPIAccessWithToken("xoxb-SLACK-BOT-TOKEN")
bot.webAPI?.authenticationTest(success: { (success) in
print(success)
}, failure: nil)
```
#### Slash Commands
After [configuring your slash command in Slack](https://my.slack.com/services/new/slash-commands) (you can also provide slash commands as part of a [Slack App](https://api.slack.com/slack-apps)), create a route, response middleware for that route, and add it to a responder:
```swift
let slackkit = SlackKit()
let middleware = ResponseMiddleware(token: "SLASH_COMMAND_TOKEN", response: SKResponse(text: "👋"))
let route = RequestRoute(path: "/hello", middleware: middleware)
let responder = SlackKitResponder(routes: [route])
slackkit.addServer(responder: responder)
```
When a user enters that slash command, it will hit your configured route and return the response you specified.
#### Message Buttons
Add [message buttons](https://api.slack.com/docs/message-buttons) to your responses for additional interactivity.
To send messages with actions, add them to an attachment and send them using the Web API:
```swift
let helloAction = Action(name: "hello", text: "🌎")
let attachment = Attachment(fallback: "Hello World", title: "Welcome to SlackKit", callbackID: "hello_world", actions: [helloAction])
slackkit.webAPI?.sendMessage(channel: "CXXXXXX", text: "", attachments: [attachment], success: nil, failure: nil)
```
To respond to message actions, add a `RequestRoute` with `MessageActionMiddleware` using your apps verification token to your `SlackKitResponder`:
```swift
let response = ResponseMiddleware(token: "SLACK_APP_VERIFICATION_TOKEN", response: SKResponse(text: "Hello, world!"))
let actionRoute = MessageActionRoute(action: helloAction, middleware: response)
let actionMiddleware = MessageActionMiddleware(token: "SLACK_APP_VERIFICATION_TOKEN", routes:[actionRoute])
let actions = RequestRoute(path: "/actions", middleware: actionMiddleware)
let responder = SlackKitResponder(routes: [actions])
slackkit.addServer(responder: responder)
```
#### OAuth
Slack has [many different oauth scopes](https://api.slack.com/docs/oauth-scopes) that can be combined in different ways. If your application does not request the proper OAuth scopes, your API calls will fail.
If you authenticate using OAuth and the Add to Slack or Sign in with Slack buttons this is handled for you.
If you wish to make OAuth requests yourself, you can generate them using the `authorizeRequest` function on `SlackKit`s `oauth` property:
```swift
func authorizeRequest(scope:[Scope], redirectURI: String, state: String = "slackkit", team: String? = nil)
```
For local development of things like OAuth, slash commands, and message buttons that require connecting over `https`, you may want to use a tool like [ngrok](https://ngrok.com) or [localtunnel](http://localtunnel.me).
#### Incoming Webhooks
After [configuring your incoming webhook in Slack](https://my.slack.com/services/new/incoming-webhook/), initialize IncomingWebhook with the provided URL and use `postMessage` to send messages.
```swift
let incoming = IncomingWebhook(url: "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX")
let message = Response(text: "Hello, World!")
incoming.postMessage(message)
```
#### Slash Commands
After [configuring your slash command in Slack](https://my.slack.com/services/new/slash-commands) (you can also provide slash commands as part of a [Slack App](https://api.slack.com/slack-apps)), initialize a webhook server with the token for the slash command, a configured route, and a response.
```swift
let response = Response(text: "Hello, World!", responseType: .inChannel)
let webhook = WebhookServer(token: "SLASH-COMMAND-TOKEN", route: "hello_world", response: response)
webhook.start()
```
When a user enters that slash command, it will hit your configured route and return the response you specified.
To add additional routes and responses, you can use WebhookServers addRoute function:
```swift
func addRoute(route: String, response: Response)
```
#### Message Buttons
If you are developing a Slack App and are authorizing using OAuth, you can use [message buttons](https://api.slack.com/docs/message-buttons).
To send messages with actions, add them to an attachment:
```swift
let helloAction = Action(name: "hello_world", text: "Hello, World!")
let attachment = Attachment(fallback: "Hello World Attachment", title: "Attachment with an Action Button", callbackID: "helloworld", actions: [helloAction])
```
To act on message actions, initialize an instance of the `MessageActionServer` using your apps verification token, your specified interactive messages request URL route, and a `MessageActionResponder`:
```swift
let action = Action(name: "hello_world", text: "Hello, World!")
let response = Response(text: "Hello, 🌎!", responseType: .inChannel)
let responder = MessageActionResponder(responses: [(action, response)])
let server = MessageActionServer(token: "SLACK-APP-VERIFICATION-TOKEN", route: "actions", responder: responder)
server.start()
```
#### Bot Users
To deploy a bot user using SlackKit you'll need a bearer token which identifies a single user. You can generate a [full access token or create one using OAuth 2](https://api.slack.com/web).
Initialize a SlackKit instance using your [applications Client ID and Client Secret](https://api.slack.com/apps) to set up SlackKit for OAuth authorization:
```swift
let bot = SlackKit(clientID: "CLIENT_ID", clientSecret: "CLIENT_SECRET")
```
or use a manually acquired token:
```swift
let bot = SlackKit(withAPIToken: "xoxp-YOUR-SLACK-API-TOKEN")
```
#### Client Connection Options
You can also set options for a ping/pong interval, timeout interval, and automatic reconnection:
```swift
let options = ClientOptions(pingInterval: 2, timeout: 10, reconnect: false)
let bot = SlackKit(clientID: "CLIENT_ID", clientSecret: "CLIENT_SECRET", clientOptions: options)
```
Once connected, the client will begin to consume any messages sent by the Slack RTM API.
For local development of things like OAuth, slash commands, and message buttons, you may want to use a tool like [ngrok](https://ngrok.com).
#### Web API Methods
SlackKit currently supports the a subset of the Slack Web APIs that are available to bot users:
- api.test
- auth.revoke
- auth.test
- channels.history
- channels.info
- channels.list
- channels.mark
- channels.setPurpose
- channels.setTopic
- chat.delete
- chat.meMessage
- chat.postMessage
- chat.update
- emoji.list
- files.comments.add
- files.comments.edit
- files.comments.delete
- files.delete
- files.info
- files.upload
- groups.close
- groups.history
- groups.info
- groups.list
- groups.mark
- groups.open
- groups.setPurpose
- groups.setTopic
- im.close
- im.history
- im.list
- im.mark
- im.open
- mpim.close
- mpim.history
- mpim.list
- mpim.mark
- mpim.open
- oauth.access
- pins.add
- pins.list
- pins.remove
- reactions.add
- reactions.get
- reactions.list
- reactions.remove
- rtm.start
- stars.add
- stars.remove
- team.info
- users.getPresence
- users.info
- users.list
- users.setActive
- users.setPresence
| Web APIs |
| ------------- |
| `api.test`|
| `api.revoke`|
| `auth.test`|
| `channels.history`|
| `channels.info`|
| `channels.list`|
| `channels.mark`|
| `channels.setPurpose`|
| `channels.setTopic`|
| `chat.delete`|
| `chat.meMessage`|
| `chat.postMessage`|
| `chat.update`|
| `emoji.list`|
| `files.comments.add`|
| `files.comments.edit`|
| `files.comments.delete`|
| `files.delete`|
| `files.info`|
| `files.upload`|
| `groups.close`|
| `groups.history`|
| `groups.info`|
| `groups.list`|
| `groups.mark`|
| `groups.open`|
| `groups.setPurpose`|
| `groups.setTopic`|
| `im.close`|
| `im.history`|
| `im.list`|
| `im.mark`|
| `im.open`|
| `mpim.close`|
| `mpim.history`|
| `mpim.list`|
| `mpim.mark`|
| `mpim.open`|
| `oauth.access`|
| `pins.add`|
| `pins.list`|
| `pins.remove`|
| `reactions.add`|
| `reactions.get`|
| `reactions.list`|
| `reactions.remove`|
| `rtm.start`|
| `stars.add`|
| `stars.remove`|
| `team.info`|
| `users.getPresence`|
| `users.info`|
| `users.list`|
| `users.setActive`|
| `users.setPresence`|
They can be accessed through a Client objects `webAPI` property:
```swift
client.webAPI.authenticationTest({(auth) in
print(auth)
}, failure: {(error) in
print(error)
})
```
Dont need the whole banana? Want more control over the low-level implementation details? Use the extensible modules SlackKit is built on:
#### Delegate methods
To receive delegate callbacks for events, register an object as the delegate for those events using the `onClientInitalization` block:
```swift
let bot = SlackKit(clientID: clientID, clientSecret: clientSecret)
bot.onClientInitalization = { (client: Client) in
DispatchQueue.main.async(execute: {
client.messageEventsDelegate = self
})
}
```
Delegate callbacks contain a reference to the Client where the event occurred.
There are a number of delegates that you can set to receive callbacks for certain events.
##### ConnectionEventsDelegate
```swift
connected(_ client: Client)
disconnected(_ client: Client)
connectionFailed(_ client: Client, error: SlackError)
```
##### MessageEventsDelegate
```swift
sent(_ message: Message, client: Client)
received(_ message: Message, client: Client)
changed(_ message: Message, client: Client)
deleted(_ message: Message?, client: Client)
```
##### ChannelEventsDelegate
```swift
userTypingIn(_ channel: Channel, user: User, client: Client)
marked(_ channel: Channel, timestamp: String, client: Client)
created(_ channel: Channel, client: Client)
deleted(_ channel: Channel, client: Client)
renamed(_ channel: Channel, client: Client)
archived(_ channel: Channel, client: Client)
historyChanged(_ channel: Channel, client: Client)
joined(_ channel: Channel, client: Client)
left(_ channel: Channel, client: Client)
```
##### DoNotDisturbEventsDelegate
```swift
updated(_ status: DoNotDisturbStatus, client: Client)
userUpdated(_ status: DoNotDisturbStatus, user: User, client: Client)
```
##### GroupEventsDelegate
```swift
opened(_ group: Channel, client: Client)
```
##### FileEventsDelegate
```swift
processed(_ file: File, client: Client)
madePrivate(_ file: File, client: Client)
deleted(_ file: File, client: Client)
commentAdded(_ file: File, comment: Comment, client: Client)
commentEdited(_ file: File, comment: Comment, client: Client)
commentDeleted(_ file: File, comment: Comment, client: Client)
```
##### PinEventsDelegate
```swift
pinned(_ item: Item, channel: Channel?, client: Client)
unpinned(_ item: Item, channel: Channel?, client: Client)
```
##### StarEventsDelegate
```swift
starred(_ item: Item, starred: Bool, _ client: Client)
```
##### ReactionEventsDelegate
```swift
added(_ reaction: String, item: Item, itemUser: String, client: Client)
removed(_ reaction: String, item: Item, itemUser: String, client: Client)
```
##### SlackEventsDelegate
```swift
preferenceChanged(_ preference: String, value: Any?, client: Client)
userChanged(_ user: User, client: Client)
presenceChanged(_ user: User, presence: String, client: Client)
manualPresenceChanged(_ user: User, presence: String, client: Client)
botEvent(_ bot: Bot, client: Client)
```
##### TeamEventsDelegate
```swift
userJoined(_ user: User, client: Client)
planChanged(_ plan: String, client: Client)
preferencesChanged(_ preference: String, value: Any?, client: Client)
nameChanged(_ name: String, client: Client)
domainChanged(_ domain: String, client: Client)
emailDomainChanged(_ domain: String, client: Client)
emojiChanged(_ client: Client)
```
##### SubteamEventsDelegate
```swift
event(_ userGroup: UserGroup, client: Client)
selfAdded(_ subteamID: String, client: Client)
selfRemoved(_ subteamID: String, client: Client)
```
##### TeamProfileEventsDelegate
```swift
changed(_ profile: CustomProfile, client: Client)
deleted(_ profile: CustomProfile, client: Client)
reordered(_ profile: CustomProfile, client: Client)
```
| Module | Slack Service |
| ------------- |------------- |
| **[SKClient](https://github.com/SlackKit/SKClient)** | Write your own client implementation|
| **[SKRTMAPI](https://github.com/SlackKit/SKRTMAPI)** | Connect to the Slack RTM API|
| **[SKServer](https://github.com/SlackKit/SKServer)** | Spin up a server|
| **[SKWebAPI](https://github.com/SlackKit/SKWebAPI)** | Access the Slack Web API|
### Examples
[Check out example applications here.](https://github.com/pvzig/SlackKit-examples)
You can find the source code for several example applications [here](https://github.com/SlackKit/Examples).
### Tutorials
- [Build a Slack Bot and Deploy to Heroku](https://medium.com/@pvzig/building-slack-bots-in-swift-b99e243e444c)
### Get In Touch
[@pvzig](https://twitter.com/pvzig)
Twitter: [@pvzig](https://twitter.com/pvzig)
<peter@launchsoft.co>
Email: <peter@launchsoft.co>
+19 -17
View File
@@ -1,18 +1,20 @@
Pod::Spec.new do |s|
s.name = "SlackKit"
s.version = "3.1.5"
s.summary = "a Slack client library for OS X, iOS, and tvOS written in Swift"
s.homepage = "https://github.com/pvzig/SlackKit"
s.license = 'MIT'
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.10'
s.tvos.deployment_target = '9.0'
s.requires_arc = true
s.source_files = 'SlackKit/Sources/*.swift'
s.frameworks = 'Foundation'
s.dependency 'Starscream'
s.dependency 'Swifter'
end
s.name = "SlackKit"
s.version = "4.1.0"
s.summary = "Write Slack apps 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/SlackKit/SlackKit.git", :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/pvzig'
s.ios.deployment_target = '9.0'
s.osx.deployment_target = '10.11'
s.tvos.deployment_target = '9.0'
s.requires_arc = true
s.source_files = 'Sources/*.swift'
s.frameworks = 'Foundation'
s.dependency 'SKCore'
s.dependency 'SKClient'
s.dependency 'SKRTMAPI'
s.dependency 'SKServer'
end
File diff suppressed because it is too large Load Diff
@@ -2,6 +2,6 @@
<Workspace
version = "1.0">
<FileRef
location = "self:SlackRTMKit.xcodeproj">
location = "self:SKCore.xcodeproj">
</FileRef>
</Workspace>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0800"
LastUpgradeVersion = "0920"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -14,7 +14,7 @@
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "263993951CE90EE0004A6E93"
BlueprintIdentifier = "2684F1C21E95ABD400536DCC"
BuildableName = "SlackKit.framework"
BlueprintName = "SlackKit iOS"
ReferencedContainer = "container:SlackKit.xcodeproj">
@@ -26,6 +26,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
@@ -36,6 +37,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
@@ -45,7 +47,7 @@
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "263993951CE90EE0004A6E93"
BlueprintIdentifier = "2684F1C21E95ABD400536DCC"
BuildableName = "SlackKit.framework"
BlueprintName = "SlackKit iOS"
ReferencedContainer = "container:SlackKit.xcodeproj">
@@ -63,7 +65,7 @@
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "263993951CE90EE0004A6E93"
BlueprintIdentifier = "2684F1C21E95ABD400536DCC"
BuildableName = "SlackKit.framework"
BlueprintName = "SlackKit iOS"
ReferencedContainer = "container:SlackKit.xcodeproj">
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0800"
LastUpgradeVersion = "0920"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -14,9 +14,9 @@
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "26072A331BB48B3A00CD650C"
BlueprintIdentifier = "2684F17C1E95AA6900536DCC"
BuildableName = "SlackKit.framework"
BlueprintName = "SlackKit OS X"
BlueprintName = "SlackKit macOS"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
@@ -26,6 +26,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
@@ -36,6 +37,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
@@ -45,9 +47,9 @@
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "26072A331BB48B3A00CD650C"
BlueprintIdentifier = "2684F17C1E95AA6900536DCC"
BuildableName = "SlackKit.framework"
BlueprintName = "SlackKit OS X"
BlueprintName = "SlackKit macOS"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</MacroExpansion>
@@ -63,9 +65,9 @@
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "26072A331BB48B3A00CD650C"
BlueprintIdentifier = "2684F17C1E95AA6900536DCC"
BuildableName = "SlackKit.framework"
BlueprintName = "SlackKit OS X"
BlueprintName = "SlackKit macOS"
ReferencedContainer = "container:SlackKit.xcodeproj">
</BuildableReference>
</MacroExpansion>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0800"
LastUpgradeVersion = "0920"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -14,7 +14,7 @@
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "263993B41CE90EED004A6E93"
BlueprintIdentifier = "2684F1E61E95ABD600536DCC"
BuildableName = "SlackKit.framework"
BlueprintName = "SlackKit tvOS"
ReferencedContainer = "container:SlackKit.xcodeproj">
@@ -26,6 +26,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
@@ -36,6 +37,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
@@ -45,7 +47,7 @@
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "263993B41CE90EED004A6E93"
BlueprintIdentifier = "2684F1E61E95ABD600536DCC"
BuildableName = "SlackKit.framework"
BlueprintName = "SlackKit tvOS"
ReferencedContainer = "container:SlackKit.xcodeproj">
@@ -63,7 +65,7 @@
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "263993B41CE90EED004A6E93"
BlueprintIdentifier = "2684F1E61E95ABD600536DCC"
BuildableName = "SlackKit.framework"
BlueprintName = "SlackKit tvOS"
ReferencedContainer = "container:SlackKit.xcodeproj">
-30
View File
@@ -1,30 +0,0 @@
//
// SlackKit.h
//
// Copyright © 2016 Peter Zignego. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
//! Project version number for SlackKit.
FOUNDATION_EXPORT double SlackKitVersionNumber;
//! Project version string for SlackKit.
FOUNDATION_EXPORT const unsigned char SlackKitVersionString[];
-103
View File
@@ -1,103 +0,0 @@
//
// Action.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 Action {
public let name: String?
public let text: String?
public let type: String?
public let value: String?
public let style: ActionStyle?
public let confirm: Confirm?
internal init(action:[String: Any]?) {
name = action?["name"] as? String
text = action?["text"] as? String
type = action?["type"] as? String
value = action?["value"] as? String
style = ActionStyle(rawValue: action?["style"] as? String ?? "")
confirm = Confirm(confirm:action?["confirm"] as? [String: Any])
}
public init(name: String, text: String, style: ActionStyle = .defaultStyle, value: String? = nil, confirm: Confirm? = nil) {
self.type = "button"
self.name = name
self.text = text
self.value = value
self.style = style
self.confirm = confirm
}
internal var dictionary: [String: Any] {
var dict = [String: Any]()
dict["name"] = name
dict["text"] = text
dict["type"] = type
dict["value"] = value
dict["style"] = style?.rawValue
dict["confirm"] = confirm?.dictionary
return dict
}
public struct Confirm {
public let title: String?
public let text: String?
public let okText: String?
public let dismissText: String?
internal init(confirm:[String: Any]?) {
title = confirm?["title"] as? String
text = confirm?["text"] as? String
okText = confirm?["ok_text"] as? String
dismissText = confirm?["dismiss_text"] as? String
}
public init(text: String, title: String? = nil, okText: String? = nil, dismissText: String? = nil) {
self.text = text
self.title = title
self.okText = okText
self.dismissText = dismissText
}
internal var dictionary: [String: Any] {
var dict = [String: Any]()
dict["title"] = title
dict["text"] = text
dict["ok_text"] = okText
dict["dismiss_text"] = dismissText
return dict
}
}
}
public enum ActionStyle: String {
case defaultStyle = "default"
case primary = "primary"
case danger = "danger"
}
public enum ResponseType: String {
case inChannel = "in_channel"
case ephemeral = "ephemeral"
}
-115
View File
@@ -1,115 +0,0 @@
//
// 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 callbackID: String?
public let type: 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 actions: [Action]?
public let imageURL: String?
public let thumbURL: String?
public let footer: String?
public let footerIcon: String?
public let ts: Int?
internal init(attachment: [String: Any]?) {
fallback = attachment?["fallback"] as? String
callbackID = attachment?["callback_id"] as? String
type = attachment?["attachment_type"] 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
footer = attachment?["footer"] as? String
footerIcon = attachment?["footer_icon"] as? String
ts = attachment?["ts"] as? Int
fields = (attachment?["fields"] as? [[String: Any]])?.map { AttachmentField(field: $0) }
actions = (attachment?["actions"] as? [[String: Any]])?.map { Action(action: $0) }
}
public init(fallback: String, title:String, callbackID: String? = nil, type: String? = nil, colorHex: String? = nil, pretext: String? = nil, authorName: String? = nil, authorLink: String? = nil, authorIcon: String? = nil, titleLink: String? = nil, text: String? = nil, fields: [AttachmentField]? = nil, actions: [Action]? = nil, imageURL: String? = nil, thumbURL: String? = nil, footer: String? = nil, footerIcon:String? = nil, ts:Int? = nil) {
self.fallback = fallback
self.callbackID = callbackID
self.type = type
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.actions = actions
self.imageURL = imageURL
self.thumbURL = thumbURL
self.footer = footer
self.footerIcon = footerIcon
self.ts = ts
}
internal var dictionary: [String: Any] {
var attachment = [String: Any]()
attachment["fallback"] = fallback
attachment["callback_id"] = callbackID
attachment["attachment_type"] = type
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"] = fields?.map{$0.dictionary}
attachment["actions"] = actions?.map{$0.dictionary}
attachment["image_url"] = imageURL
attachment["thumb_url"] = thumbURL
attachment["footer"] = footer
attachment["footer_icon"] = footerIcon
attachment["ts"] = ts
return attachment
}
}
public enum AttachmentColor: String {
case good = "good"
case warning = "warning"
case danger = "danger"
}
-49
View File
@@ -1,49 +0,0 @@
//
// AttachmentField.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 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 var dictionary: [String: Any] {
var field = [String: Any]()
field["title"] = title
field["value"] = value
field["short"] = short
return field
}
}
-47
View File
@@ -1,47 +0,0 @@
//
// AuthorizeRequest.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.
internal struct AuthorizeRequest {
let clientID: String
let scope: [Scope]
let redirectURI: String
let state: String
let team: String?
var parameters: [String: Any] {
var json = [String : Any]()
json["scope"] = scope.map({$0.rawValue}).joined(separator: ",")
json["state"] = state
json["team"] = team
return json
}
init(clientID: String, scope:[Scope], redirectURI: String, state: String = "slackkit", team: String? = nil) {
self.clientID = clientID
self.scope = scope
self.redirectURI = redirectURI
self.state = state
self.team = team
}
}
-36
View File
@@ -1,36 +0,0 @@
//
// AuthorizeResponse.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.
internal struct AuthorizeResponse {
let code: String
let state: String
init?(queryParameters: [(String, String)]) {
guard let code = queryParameters.first?.1, let state = queryParameters.last?.1 else {
return nil
}
self.code = code
self.state = state
}
}
-41
View File
@@ -1,41 +0,0 @@
//
// Bot.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 Bot {
public let id: String?
internal(set) public var botToken: String?
internal(set) public var name: String?
internal(set) public var icons: [String: Any]?
internal init(bot: [String: Any]?) {
id = bot?["id"] as? String
name = bot?["name"] as? String
icons = bot?["icons"] as? [String: Any]
}
internal init(botUser: [String: Any]?) {
id = botUser?["bot_user_id"] as? String
botToken = botUser?["bot_access_token"] as? String
}
}
-89
View File
@@ -1,89 +0,0 @@
//
// Channel.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 Channel {
public let id: String?
public let created: Int?
public let creator: String?
internal(set) public var name: String?
internal(set) public var isArchived: Bool?
internal(set) public var isGeneral: Bool?
public let isGroup: Bool?
public let isIM: Bool?
public let isMPIM: Bool?
internal(set) public var user: String?
internal(set) public var isUserDeleted: Bool?
internal(set) public var isOpen: Bool?
internal(set) public var topic: Topic?
internal(set) public var purpose: Topic?
internal(set) public var isMember: Bool?
public var lastRead: String?
internal(set) public var latest: Message?
public var unread: Int?
public var unreadCountDisplay: Int?
internal(set) public var hasPins: Bool?
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: Any]?) {
id = channel?["id"] as? String
name = channel?["name"] as? String
created = channel?["created"] as? Int
creator = channel?["creator"] as? String
isArchived = channel?["is_archived"] as? Bool
isGeneral = channel?["is_general"] as? Bool
isGroup = channel?["is_group"] as? Bool
isIM = channel?["is_im"] as? Bool
isMPIM = channel?["is_mpim"] as? Bool
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: Any])
purpose = Topic(topic: channel?["purpose"] as? [String: Any])
isMember = channel?["is_member"] as? Bool
lastRead = channel?["last_read"] as? String
unread = channel?["unread_count"] as? Int
unreadCountDisplay = channel?["unread_count_display"] as? Int
hasPins = channel?["has_pins"] as? Bool
members = channel?["members"] as? [String]
if let latestMesssageDictionary = channel?["latest"] as? [String: Any] {
latest = Message(dictionary: latestMesssageDictionary)
} else {
latest = Message(ts: channel?["latest"] as? String)
}
}
internal init(id:String?) {
self.id = id
created = nil
creator = nil
isGroup = false
isIM = false
isMPIM = false
}
}
@@ -1,173 +0,0 @@
//
// Client+EventDispatching.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.
internal extension Client {
func dispatch(_ event: [String: Any]) {
let event = Event(event)
let type = event.type ?? .error
switch type {
case .hello:
connected = true
connectionEventsDelegate?.connected(self)
case .ok:
messageSent(event)
case .message:
if (event.subtype != nil) {
messageDispatcher(event)
} else {
messageReceived(event)
}
case .userTyping:
userTyping(event)
case .channelMarked, .imMarked, .groupMarked:
channelMarked(event)
case .channelCreated, .imCreated:
channelCreated(event)
case .channelJoined, .groupJoined:
channelJoined(event)
case .channelLeft, .groupLeft:
channelLeft(event)
case .channelDeleted:
channelDeleted(event)
case .channelRenamed, .groupRename:
channelRenamed(event)
case .channelArchive, .groupArchive:
channelArchived(event, archived: true)
case .channelUnarchive, .groupUnarchive:
channelArchived(event, archived: false)
case .channelHistoryChanged, .imHistoryChanged, .groupHistoryChanged:
channelHistoryChanged(event)
case .dndUpdated:
doNotDisturbUpdated(event)
case .dndUpatedUser:
doNotDisturbUserUpdated(event)
case .imOpen, .groupOpen:
open(event, open: true)
case .imClose, .groupClose:
open(event, open: false)
case .fileCreated:
processFile(event)
case .fileShared:
processFile(event)
case .fileUnshared:
processFile(event)
case .filePublic:
processFile(event)
case .filePrivate:
filePrivate(event)
case .fileChanged:
processFile(event)
case .fileDeleted:
deleteFile(event)
case .fileCommentAdded:
fileCommentAdded(event)
case .fileCommentEdited:
fileCommentEdited(event)
case .fileCommentDeleted:
fileCommentDeleted(event)
case .pinAdded:
pinAdded(event)
case .pinRemoved:
pinRemoved(event)
case .pong:
pong(event)
case .presenceChange:
presenceChange(event)
case .manualPresenceChange:
manualPresenceChange(event)
case .prefChange:
changePreference(event)
case .userChange:
userChange(event)
case .teamJoin:
teamJoin(event)
case .starAdded:
itemStarred(event, star: true)
case .starRemoved:
itemStarred(event, star: false)
case .reactionAdded:
addedReaction(event)
case .reactionRemoved:
removedReaction(event)
case .emojiChanged:
emojiChanged(event)
case .commandsChanged:
// This functionality is only used by our web client.
// The other APIs required to support slash command metadata are currently unstable.
// Until they are released other clients should ignore this event.
break
case .teamPlanChange:
teamPlanChange(event)
case .teamPrefChange:
teamPreferenceChange(event)
case .teamRename:
teamNameChange(event)
case .teamDomainChange:
teamDomainChange(event)
case .emailDomainChange:
emailDomainChange(event)
case .teamProfileChange:
teamProfileChange(event)
case .teamProfileDelete:
teamProfileDeleted(event)
case .teamProfileReorder:
teamProfileReordered(event)
case .botAdded:
bot(event)
case .botChanged:
bot(event)
case .accountsChanged:
// The accounts_changed event is used by our web client to maintain a list of logged-in accounts.
// Other clients should ignore this event.
break
case .teamMigrationStarted:
connect(options: options ?? ClientOptions())
case .reconnectURL:
// The reconnect_url event is currently unsupported and experimental.
break
case .subteamCreated, .subteamUpdated:
subteam(event)
case .subteamSelfAdded:
subteamAddedSelf(event)
case .subteamSelfRemoved:
subteamRemovedSelf(event)
case .error:
print("Error: \(event)")
}
}
func messageDispatcher(_ event:Event) {
guard let value = event.subtype, let subtype = MessageSubtype(rawValue:value) else {
return
}
switch subtype {
case .messageChanged:
messageChanged(event)
case .messageDeleted:
messageDeleted(event)
default:
messageReceived(event)
}
}
}
-562
View File
@@ -1,562 +0,0 @@
//
// Client+EventHandling.swift
//
// Copyright © 2016 Peter Zignego. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
internal extension Client {
//MARK: - Pong
func pong(_ event: Event) {
pong = event.replyTo
}
//MARK: - Messages
func messageSent(_ event: Event) {
guard let reply = event.replyTo, let message = sentMessages[NSNumber(value: reply).stringValue], let channel = message.channel, let ts = message.ts else {
return
}
message.ts = event.ts
message.text = event.text
channels[channel]?.messages[ts] = message
messageEventsDelegate?.sent(message, client: self)
}
func messageReceived(_ event: Event) {
guard let channel = event.channel, let message = event.message, let id = channel.id, let ts = message.ts else {
return
}
channels[id]?.messages[ts] = message
messageEventsDelegate?.received(message, client:self)
}
func messageChanged(_ event: Event) {
guard let id = event.channel?.id, let nested = event.nestedMessage, let ts = nested.ts else {
return
}
channels[id]?.messages[ts] = nested
messageEventsDelegate?.changed(nested, client:self)
}
func messageDeleted(_ event: Event) {
guard let id = event.channel?.id, let key = event.message?.deletedTs, let message = channels[id]?.messages[key] else {
return
}
_ = channels[id]?.messages.removeValue(forKey: key)
messageEventsDelegate?.deleted(message, client:self)
}
//MARK: - Channels
func userTyping(_ event: Event) {
guard let channel = event.channel, let channelID = channel.id, let user = event.user, let userID = user.id ,
channels.index(forKey: channelID) != nil && !channels[channelID]!.usersTyping.contains(userID) else {
return
}
channels[channelID]?.usersTyping.append(userID)
channelEventsDelegate?.userTypingIn(channel, user: user, client: self)
let timeout = DispatchTime.now() + Double(Int64(5.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: timeout, execute: {
if let index = self.channels[channelID]?.usersTyping.index(of: userID) {
self.channels[channelID]?.usersTyping.remove(at: index)
}
})
}
func channelMarked(_ event: Event) {
guard let channel = event.channel, let id = channel.id, let timestamp = event.ts else {
return
}
channels[id]?.lastRead = event.ts
channelEventsDelegate?.marked(channel, timestamp: timestamp, client: self)
}
func channelCreated(_ event: Event) {
guard let channel = event.channel, let id = channel.id else {
return
}
channels[id] = channel
channelEventsDelegate?.created(channel, client: self)
}
func channelDeleted(_ event: Event) {
guard let channel = event.channel, let id = channel.id else {
return
}
channels.removeValue(forKey: id)
channelEventsDelegate?.deleted(channel, client: self)
}
func channelJoined(_ event: Event) {
guard let channel = event.channel, let id = channel.id else {
return
}
channels[id] = event.channel
channelEventsDelegate?.joined(channel, client: self)
}
func channelLeft(_ event: Event) {
guard let channel = event.channel, let id = channel.id else {
return
}
if let userID = authenticatedUser?.id, let index = channels[id]?.members?.index(of: userID) {
channels[id]?.members?.remove(at: index)
}
channelEventsDelegate?.left(channel, client: self)
}
func channelRenamed(_ event: Event) {
guard let channel = event.channel, let id = channel.id else {
return
}
channels[id]?.name = channel.name
channelEventsDelegate?.renamed(channel, client: self)
}
func channelArchived(_ event: Event, archived: Bool) {
guard let channel = event.channel, let id = channel.id else {
return
}
channels[id]?.isArchived = archived
channelEventsDelegate?.archived(channel, client: self)
}
func channelHistoryChanged(_ event: Event) {
guard let channel = event.channel else {
return
}
channelEventsDelegate?.historyChanged(channel, client: self)
}
//MARK: - Do Not Disturb
func doNotDisturbUpdated(_ event: Event) {
guard let dndStatus = event.dndStatus else {
return
}
authenticatedUser?.doNotDisturbStatus = dndStatus
doNotDisturbEventsDelegate?.updated(dndStatus, client: self)
}
func doNotDisturbUserUpdated(_ event: Event) {
guard let dndStatus = event.dndStatus, let user = event.user, let id = user.id else {
return
}
users[id]?.doNotDisturbStatus = dndStatus
doNotDisturbEventsDelegate?.userUpdated(dndStatus, user: user, client: self)
}
//MARK: - IM & Group Open/Close
func open(_ event: Event, open: Bool) {
guard let channel = event.channel, let id = channel.id else {
return
}
channels[id]?.isOpen = open
groupEventsDelegate?.opened(channel, client: self)
}
//MARK: - Files
func processFile(_ event: Event) {
guard let file = event.file, let id = file.id else {
return
}
if let comment = file.initialComment, let commentID = comment.id {
if files[id]?.comments[commentID] == nil {
files[id]?.comments[commentID] = comment
}
}
files[id] = file
fileEventsDelegate?.processed(file, client: self)
}
func filePrivate(_ event: Event) {
guard let file = event.file, let id = file.id else {
return
}
files[id]?.isPublic = false
fileEventsDelegate?.madePrivate(file, client: self)
}
func deleteFile(_ event: Event) {
guard let file = event.file, let id = file.id else {
return
}
if files[id] != nil {
files.removeValue(forKey: id)
}
fileEventsDelegate?.deleted(file, client: self)
}
func fileCommentAdded(_ event: Event) {
guard let file = event.file, let id = file.id, let comment = event.comment, let commentID = comment.id else {
return
}
files[id]?.comments[commentID] = comment
fileEventsDelegate?.commentAdded(file, comment: comment, client: self)
}
func fileCommentEdited(_ event: Event) {
guard let file = event.file, let id = file.id, let comment = event.comment, let commentID = comment.id else {
return
}
files[id]?.comments[commentID]?.comment = comment.comment
fileEventsDelegate?.commentAdded(file, comment: comment, client: self)
}
func fileCommentDeleted(_ event: Event) {
guard let file = event.file, let id = file.id, let comment = event.comment, let commentID = comment.id else {
return
}
_ = files[id]?.comments.removeValue(forKey: commentID)
fileEventsDelegate?.commentDeleted(file, comment: comment, client: self)
}
//MARK: - Pins
func pinAdded(_ event: Event) {
guard let id = event.channelID, let item = event.item else {
return
}
channels[id]?.pinnedItems.append(item)
pinEventsDelegate?.pinned(item, channel: channels[id], client: self)
}
func pinRemoved(_ event: Event) {
guard let id = event.channelID, let item = event.item else {
return
}
if let pins = channels[id]?.pinnedItems.filter({$0 != item}) {
channels[id]?.pinnedItems = pins
}
pinEventsDelegate?.unpinned(item, channel: channels[id], client: self)
}
//MARK: - Stars
func itemStarred(_ event: Event, star: Bool) {
guard let item = event.item, let type = item.type else {
return
}
switch type {
case "message":
starMessage(item, star: star)
case "file":
starFile(item, star: star)
case "file_comment":
starComment(item)
default:
break
}
starEventsDelegate?.starred(item, starred: star, self)
}
func starMessage(_ item: Item, star: Bool) {
guard let message = item.message, let ts = message.ts, let channel = item.channel , channels[channel]?.messages[ts] != nil else {
return
}
channels[channel]?.messages[ts]?.isStarred = star
}
func starFile(_ item: Item, star: Bool) {
guard let file = item.file, let id = file.id else {
return
}
files[id]?.isStarred = star
if let stars = files[id]?.stars {
if star == true {
files[id]?.stars = stars + 1
} else {
if stars > 0 {
files[id]?.stars = stars - 1
}
}
}
}
func starComment(_ item: Item) {
guard let file = item.file, let id = file.id, let comment = item.comment, let commentID = comment.id else {
return
}
files[id]?.comments[commentID] = comment
}
//MARK: - Reactions
func addedReaction(_ event: Event) {
guard let item = event.item, let type = item.type, let reaction = event.reaction, let userID = event.user?.id, let itemUser = event.itemUser else {
return
}
switch type {
case "message":
guard let channel = item.channel, let ts = item.ts, let message = channels[channel]?.messages[ts] else {
return
}
message.reactions.append(Reaction(name: reaction, user: userID))
case "file":
guard let id = item.file?.id else {
return
}
files[id]?.reactions.append(Reaction(name: reaction, user: userID))
case "file_comment":
guard let id = item.file?.id, let commentID = item.fileCommentID else {
return
}
files[id]?.comments[commentID]?.reactions.append(Reaction(name: reaction, user: userID))
default:
break
}
reactionEventsDelegate?.added(reaction, item: item, itemUser: itemUser, client: self)
}
func removedReaction(_ event: Event) {
guard let item = event.item, let type = item.type, let key = event.reaction, let userID = event.user?.id, let itemUser = event.itemUser else {
return
}
switch type {
case "message":
guard let channel = item.channel, let ts = item.ts, let message = channels[channel]?.messages[ts] else {
return
}
message.reactions = message.reactions.filter({$0.name != key && $0.user != userID})
case "file":
guard let itemFile = item.file, let id = itemFile.id else {
return
}
files[id]?.reactions = files[id]!.reactions.filter({$0.name != key && $0.user != userID})
case "file_comment":
guard let id = item.file?.id, let commentID = item.fileCommentID else {
return
}
files[id]?.comments[commentID]?.reactions = files[id]!.comments[commentID]!.reactions.filter({$0.name != key && $0.user != userID})
default:
break
}
reactionEventsDelegate?.removed(key, item: item, itemUser: itemUser, client: self)
}
//MARK: - Preferences
func changePreference(_ event: Event) {
guard let name = event.name else {
return
}
authenticatedUser?.preferences?[name] = event.value
slackEventsDelegate?.preferenceChanged(name, value: event.value, client: self)
}
//Mark: - User Change
func userChange(_ event: Event) {
guard let user = event.user, let id = user.id else {
return
}
let preferences = users[id]?.preferences
users[id] = user
users[id]?.preferences = preferences
slackEventsDelegate?.userChanged(user, client: self)
}
//MARK: - User Presence
func presenceChange(_ event: Event) {
guard let user = event.user, let id = user.id, let presence = event.presence else {
return
}
users[id]?.presence = event.presence
slackEventsDelegate?.presenceChanged(user, presence: presence, client: self)
}
//MARK: - Team
func teamJoin(_ event: Event) {
guard let user = event.user, let id = user.id else {
return
}
users[id] = user
teamEventsDelegate?.userJoined(user, client: self)
}
func teamPlanChange(_ event: Event) {
guard let plan = event.plan else {
return
}
team?.plan = plan
teamEventsDelegate?.planChanged(plan, client: self)
}
func teamPreferenceChange(_ event: Event) {
guard let name = event.name else {
return
}
team?.prefs?[name] = event.value
teamEventsDelegate?.preferencesChanged(name, value: event.value, client: self)
}
func teamNameChange(_ event: Event) {
guard let name = event.name else {
return
}
team?.name = name
teamEventsDelegate?.nameChanged(name, client: self)
}
func teamDomainChange(_ event: Event) {
guard let domain = event.domain else {
return
}
team?.domain = domain
teamEventsDelegate?.domainChanged(domain, client: self)
}
func emailDomainChange(_ event: Event) {
guard let domain = event.emailDomain else {
return
}
team?.emailDomain = domain
teamEventsDelegate?.emailDomainChanged(domain, client: self)
}
func emojiChanged(_ event: Event) {
teamEventsDelegate?.emojiChanged(self)
}
//MARK: - Bots
func bot(_ event: Event) {
guard let bot = event.bot, let id = bot.id else {
return
}
bots[id] = bot
slackEventsDelegate?.botEvent(bot, client: self)
}
//MARK: - Subteams
func subteam(_ event: Event) {
guard let subteam = event.subteam, let id = subteam.id else {
return
}
userGroups[id] = subteam
subteamEventsDelegate?.event(subteam, client: self)
}
func subteamAddedSelf(_ event: Event) {
guard let subteamID = event.subteamID, let _ = authenticatedUser?.userGroups else {
return
}
authenticatedUser?.userGroups![subteamID] = subteamID
subteamEventsDelegate?.selfAdded(subteamID, client: self)
}
func subteamRemovedSelf(_ event: Event) {
guard let subteamID = event.subteamID else {
return
}
_ = authenticatedUser?.userGroups?.removeValue(forKey: subteamID)
subteamEventsDelegate?.selfRemoved(subteamID, client: self)
}
//MARK: - Team Profiles
func teamProfileChange(_ event: Event) {
guard let profile = event.profile else {
return
}
for user in users {
for key in profile.fields.keys {
users[user.0]?.profile?.customProfile?.fields[key]?.updateProfileField(profile.fields[key])
}
}
teamProfileEventsDelegate?.changed(profile, client: self)
}
func teamProfileDeleted(_ event: Event) {
guard let profile = event.profile else {
return
}
for user in users {
if let id = profile.fields.first?.0 {
users[user.0]?.profile?.customProfile?.fields[id] = nil
}
}
teamProfileEventsDelegate?.deleted(profile, client: self)
}
func teamProfileReordered(_ event: Event) {
guard let profile = event.profile else {
return
}
for user in users {
for key in profile.fields.keys {
users[user.0]?.profile?.customProfile?.fields[key]?.ordering = profile.fields[key]?.ordering
}
}
teamProfileEventsDelegate?.reordered(profile, client: self)
}
//MARK: - Authenticated User
func manualPresenceChange(_ event: Event) {
guard let presence = event.presence, let user = authenticatedUser else {
return
}
authenticatedUser?.presence = presence
slackEventsDelegate?.manualPresenceChanged(user, presence: presence, client: self)
}
}
-64
View File
@@ -1,64 +0,0 @@
//
// Client+Utilities.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 enum ClientError: Error {
case channelDoesNotExist
case userDoesNotExist
}
public extension Client {
//MARK: - User & Channel
public func getChannelIDWith(name: String) throws -> String {
guard let id = channels.filter({$0.1.name == strip(string:name)}).first?.0 else {
throw ClientError.channelDoesNotExist
}
return id
}
public func getUserIDWith(name: String) throws -> String {
guard let id = users.filter({$0.1.name == strip(string:name)}).first?.0 else {
throw ClientError.userDoesNotExist
}
return id
}
public func getImIDForUserWith(id: String, success: @escaping (_ imID: String?)->Void, failure: @escaping (SlackError)->Void) {
let ims = channels.filter{$0.1.isIM == true}
let channel = ims.filter{$0.1.user == id}.first
if let channel = channel {
success(channel.0)
} else {
webAPI.openIM(id, success: success, failure: failure)
}
}
//MARK: - Utilities
internal func strip(string: String) -> String {
var strippedString = string
if string[string.startIndex] == "@" || string[string.startIndex] == "#" {
strippedString = string.substring(from: string.characters.index(string.startIndex, offsetBy: 1))
}
return strippedString
}
}
-263
View File
@@ -1,263 +0,0 @@
//
// Client.swift
//
// Copyright © 2016 Peter Zignego. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Starscream
public final class Client: WebSocketDelegate {
internal(set) public var connected = false
internal(set) public var authenticatedUser: User?
internal(set) public var team: Team?
internal(set) public var channels = [String: Channel]()
internal(set) public var users = [String: User]()
internal(set) public var userGroups = [String: UserGroup]()
internal(set) public var bots = [String: Bot]()
internal(set) public var files = [String: File]()
internal(set) public var sentMessages = [String: Message]()
public var token = "xoxp-SLACK_AUTH_TOKEN"
public var webAPI: WebAPI {
return WebAPI(token: token)
}
internal var webSocket: WebSocket?
private let pingPongQueue = DispatchQueue(label: "com.launchsoft.SlackKit")
internal var ping: Double?
internal var pong: Double?
internal var options: ClientOptions?
//MARK: - Delegates
public weak var connectionEventsDelegate: ConnectionEventsDelegate?
public weak var slackEventsDelegate: SlackEventsDelegate?
public weak var messageEventsDelegate: MessageEventsDelegate?
public weak var doNotDisturbEventsDelegate: DoNotDisturbEventsDelegate?
public weak var channelEventsDelegate: ChannelEventsDelegate?
public weak var groupEventsDelegate: GroupEventsDelegate?
public weak var fileEventsDelegate: FileEventsDelegate?
public weak var pinEventsDelegate: PinEventsDelegate?
public weak var starEventsDelegate: StarEventsDelegate?
public weak var reactionEventsDelegate: ReactionEventsDelegate?
public weak var teamEventsDelegate: TeamEventsDelegate?
public weak var subteamEventsDelegate: SubteamEventsDelegate?
public weak var teamProfileEventsDelegate: TeamProfileEventsDelegate?
// If you already have an API token
internal init(apiToken: String) {
self.token = apiToken
}
public func setAuthToken(_ token: String) {
self.token = token
}
public func connect(options: ClientOptions = ClientOptions()) {
self.options = options
webAPI.rtmStart(options.simpleLatest, noUnreads: options.noUnreads, mpimAware: options.mpimAware, success: {(response) in
guard let socketURL = response["url"] as? String, let url = URL(string: socketURL) else {
return
}
self.initialSetup(JSON: response)
self.webSocket = WebSocket(url: url)
self.webSocket?.delegate = self
self.webSocket?.connect()
}, failure: {(error) in
self.connectionEventsDelegate?.connectionFailed(self, error: error)
})
}
public func disconnect() {
webSocket?.disconnect()
}
//MARK: - RTM Message send
public func send(message: String, channelID: String) {
guard connected else { return }
if let data = try? format(message: message, channel: channelID), let string = String(data: data, encoding: String.Encoding.utf8) {
webSocket?.write(string: string)
}
}
private func format(message: String, channel: String) throws -> Data {
let json: [String: Any] = [
"id": Date().slackTimestamp,
"type": "message",
"channel": channel,
"text": message.slackFormatEscaping
]
addSentMessage(json)
return try JSONSerialization.data(withJSONObject: json, options: [])
}
private func addSentMessage(_ dictionary: [String: Any]) {
var message = dictionary
guard let id = message["id"] as? NSNumber else {
return
}
let ts = String(describing: id)
message.removeValue(forKey: "id")
message["ts"] = ts
message["user"] = self.authenticatedUser?.id
sentMessages[ts] = Message(dictionary: message)
}
//MARK: - RTM Ping
private func pingRTMServerAt(interval: TimeInterval) {
let delay = DispatchTime.now() + Double(Int64(interval * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
pingPongQueue.asyncAfter(deadline: delay, execute: {
guard self.connected && self.timeoutCheck() else {
self.disconnect()
return
}
self.sendRTMPing()
self.pingRTMServerAt(interval: interval)
})
}
private func sendRTMPing() {
guard connected else {
return
}
let json: [String: Any] = [
"id": Date().slackTimestamp,
"type": "ping"
]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: []) else {
return
}
if let string = String(data: data, encoding: String.Encoding.utf8) {
ping = json["id"] as? Double
webSocket?.write(string: string)
}
}
private func timeoutCheck() -> Bool {
if let pong = pong, let ping = ping, let timeout = options?.timeout {
if pong - ping < timeout {
return true
} else {
return false
}
// Ping-pong or timeout not configured
} else {
return true
}
}
//MARK: - Client setup
private func initialSetup(JSON: [String: Any]) {
team = Team(team: JSON["team"] as? [String: Any])
authenticatedUser = User(user: JSON["self"] as? [String: Any])
authenticatedUser?.doNotDisturbStatus = DoNotDisturbStatus(status: JSON["dnd"] as? [String: Any])
enumerateObjects(JSON["users"] as? Array) { (user) in self.addUser(user) }
enumerateObjects(JSON["channels"] as? Array) { (channel) in self.addChannel(channel) }
enumerateObjects(JSON["groups"] as? Array) { (group) in self.addChannel(group) }
enumerateObjects(JSON["mpims"] as? Array) { (mpim) in self.addChannel(mpim) }
enumerateObjects(JSON["ims"] as? Array) { (ims) in self.addChannel(ims) }
enumerateObjects(JSON["bots"] as? Array) { (bots) in self.addBot(bots) }
enumerateSubteams(JSON["subteams"] as? [String: Any])
}
private func addUser(_ aUser: [String: Any]) {
let user = User(user: aUser)
if let id = user.id {
users[id] = user
}
}
private func addChannel(_ aChannel: [String: Any]) {
let channel = Channel(channel: aChannel)
if let id = channel.id {
channels[id] = channel
}
}
private func addBot(_ aBot: [String: Any]) {
let bot = Bot(bot: aBot)
if let id = bot.id {
bots[id] = bot
}
}
private func enumerateSubteams(_ subteams: [String: Any]?) {
if let subteams = subteams {
if let all = subteams["all"] as? [[String: Any]] {
for item in all {
let u = UserGroup(userGroup: item)
if let id = u.id {
self.userGroups[id] = u
}
}
}
if let auth = subteams["self"] as? [String] {
for item in auth {
authenticatedUser?.userGroups = [String: String]()
authenticatedUser?.userGroups?[item] = item
}
}
}
}
// 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)
}
}
}
}
// MARK: - WebSocketDelegate
public func websocketDidConnect(socket: WebSocket) {
if let pingInterval = options?.pingInterval {
pingRTMServerAt(interval: pingInterval)
}
}
public func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
connected = false
webSocket = nil
authenticatedUser = nil
connectionEventsDelegate?.disconnected(self)
if let options = options, options.reconnect == true {
connect(options: options)
}
}
public func websocketDidReceiveMessage(socket: WebSocket, text: String) {
guard let data = text.data(using: String.Encoding.utf8) else {
return
}
if let json = (try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)) as? [String: Any] {
dispatch(json)
}
}
public func websocketDidReceiveData(socket: WebSocket, data: Data) {}
}
-43
View File
@@ -1,43 +0,0 @@
//
// ClientOptions.swift
//
// Copyright © 2016 Peter Zignego. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public struct ClientOptions {
let simpleLatest: Bool?
let noUnreads: Bool?
let mpimAware: Bool?
let pingInterval: TimeInterval?
let timeout: TimeInterval?
let reconnect: Bool?
public init(simpleLatest: Bool? = nil, noUnreads: Bool? = nil, mpimAware: Bool? = nil, pingInterval: TimeInterval? = nil, timeout: TimeInterval? = nil, reconnect: Bool? = nil) {
self.simpleLatest = simpleLatest
self.noUnreads = noUnreads
self.mpimAware = mpimAware
self.pingInterval = pingInterval
self.timeout = timeout
self.reconnect = reconnect
}
}
-51
View File
@@ -1,51 +0,0 @@
//
// Comment.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 Comment: Equatable {
public let id: String?
public let user: String?
internal(set) public var created: Int?
internal(set) public var comment: String?
internal(set) public var starred: Bool?
internal(set) public var stars: Int?
internal(set) public var reactions = [Reaction]()
internal init(comment:[String: Any]?) {
id = comment?["id"] as? String
created = comment?["created"] as? Int
user = comment?["user"] as? String
starred = comment?["is_starred"] as? Bool
stars = comment?["num_stars"] as? Int
self.comment = comment?["comment"] as? String
}
internal init(id: String?) {
self.id = id
self.user = nil
}
public static func ==(lhs: Comment, rhs: Comment) -> Bool {
return lhs.id == rhs.id
}
}
-50
View File
@@ -1,50 +0,0 @@
//
// CustomProfile.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 CustomProfile {
internal(set) public var fields = [String: CustomProfileField]()
internal init(profile: [String: Any]?) {
if let eventFields = profile?["fields"] as? [Any] {
for field in eventFields {
var cpf: CustomProfileField?
if let fieldDictionary = field as? [String: Any] {
cpf = CustomProfileField(field: fieldDictionary)
} else {
cpf = CustomProfileField(id: field as? String)
}
if let id = cpf?.id { fields[id] = cpf }
}
}
}
internal init(customFields: [String: Any]?) {
if let customFields = customFields {
for key in customFields.keys {
let cpf = CustomProfileField(field: customFields[key] as? [String: Any])
self.fields[key] = cpf
}
}
}
}
-66
View File
@@ -1,66 +0,0 @@
//
// CustomProfileField.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 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
}
}
-39
View File
@@ -1,39 +0,0 @@
//
// DoNotDisturbStatus.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 DoNotDisturbStatus {
internal(set) public var enabled: Bool?
internal(set) public var nextDoNotDisturbStart: Int?
internal(set) public var nextDoNotDisturbEnd: Int?
internal(set) public var snoozeEnabled: Bool?
internal(set) public var snoozeEndtime: Int?
internal init(status: [String: Any]?) {
enabled = status?["dnd_enabled"] as? Bool
nextDoNotDisturbStart = status?["next_dnd_start_ts"] as? Int
nextDoNotDisturbEnd = status?["next_dnd_end_ts"] as? Int
snoozeEnabled = status?["snooze_enabled"] as? Bool
snoozeEndtime = status?["snooze_endtime"] as? Int
}
}
-33
View File
@@ -1,33 +0,0 @@
//
// Edited.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 Edited {
public let user: String?
public let ts: String?
internal init(edited:[String: Any]?) {
user = edited?["user"] as? String
ts = edited?["ts"] as? String
}
}
-218
View File
@@ -1,218 +0,0 @@
//
// Event.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.
internal enum EventType: String {
case hello = "hello"
case message = "message"
case userTyping = "user_typing"
case channelMarked = "channel_marked"
case channelCreated = "channel_created"
case channelJoined = "channel_joined"
case channelLeft = "channel_left"
case channelDeleted = "channel_deleted"
case channelRenamed = "channel_rename"
case channelArchive = "channel_archive"
case channelUnarchive = "channel_unarchive"
case channelHistoryChanged = "channel_history_changed"
case dndUpdated = "dnd_updated"
case dndUpatedUser = "dnd_updated_user"
case imCreated = "im_created"
case imOpen = "im_open"
case imClose = "im_close"
case imMarked = "im_marked"
case imHistoryChanged = "im_history_changed"
case groupJoined = "group_joined"
case groupLeft = "group_left"
case groupOpen = "group_open"
case groupClose = "group_close"
case groupArchive = "group_archive"
case groupUnarchive = "group_unarchive"
case groupRename = "group_rename"
case groupMarked = "group_marked"
case groupHistoryChanged = "group_history_changed"
case fileCreated = "file_created"
case fileShared = "file_shared"
case fileUnshared = "file_unshared"
case filePublic = "file_public"
case filePrivate = "file_private"
case fileChanged = "file_change"
case fileDeleted = "file_deleted"
case fileCommentAdded = "file_comment_added"
case fileCommentEdited = "file_comment_edited"
case fileCommentDeleted = "file_comment_deleted"
case pinAdded = "pin_added"
case pinRemoved = "pin_removed"
case pong = "pong"
case presenceChange = "presence_change"
case manualPresenceChange = "manual_presence_change"
case prefChange = "pref_change"
case userChange = "user_change"
case teamJoin = "team_join"
case starAdded = "star_added"
case starRemoved = "star_removed"
case reactionAdded = "reaction_added"
case reactionRemoved = "reaction_removed"
case emojiChanged = "emoji_changed"
case commandsChanged = "commands_changed"
case teamPlanChange = "team_plan_change"
case teamPrefChange = "team_pref_change"
case teamRename = "team_rename"
case teamDomainChange = "team_domain_change"
case emailDomainChange = "email_domain_change"
case teamProfileChange = "team_profile_change"
case teamProfileDelete = "team_profile_delete"
case teamProfileReorder = "team_profile_reorder"
case botAdded = "bot_added"
case botChanged = "bot_changed"
case accountsChanged = "accounts_changed"
case teamMigrationStarted = "team_migration_started"
case reconnectURL = "reconnect_url"
case subteamCreated = "subteam_created"
case subteamUpdated = "subteam_updated"
case subteamSelfAdded = "subteam_self_added"
case subteamSelfRemoved = "subteam_self_removed"
case ok = "ok"
case error = "error"
}
internal enum MessageSubtype: String {
case botMessage = "bot_message"
case meMessage = "me_message"
case messageChanged = "message_changed"
case messageDeleted = "message_deleted"
case channelJoin = "channel_join"
case channelLeave = "channel_leave"
case channelTopic = "channel_topic"
case channelPurpose = "channel_purpose"
case channelName = "channel_name"
case channelArchive = "channel_archive"
case channelUnarchive = "channel_unarchive"
case groupJoin = "group_join"
case groupLeave = "group_leave"
case groupTopic = "group_topic"
case groupPurpose = "group_purpose"
case groupName = "group_name"
case groupArchive = "group_archive"
case groupUnarchive = "group_unarchive"
case fileShare = "file_share"
case fileComment = "file_comment"
case fileMention = "file_mention"
case pinnedItem = "pinned_item"
case unpinnedItem = "unpinned_item"
}
internal class Event {
let type: EventType?
let ts: String?
let subtype: String?
let channelID: String?
let text: String?
let eventTs: String?
let latest: String?
let hidden: Bool?
let isStarred: Bool?
let hasPins: Bool?
let pinnedTo: [String]?
let fileID: String?
let presence: String?
let name: String?
let value: Any?
let plan: String?
let url: String?
let domain: String?
let emailDomain: String?
let reaction: String?
let replyTo: Double?
let reactions: [[String: Any]]?
let edited: Edited?
let bot: Bot?
let channel: Channel?
let comment: Comment?
let user: User?
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: Any]) {
type = EventType(rawValue: event["type"] as? String ?? "ok")
ts = event["ts"] as? String
subtype = event["subtype"] as? String
channelID = event["channel_id"] as? String
text = event["text"] as? String
eventTs = event["event_ts"] as? String
latest = event["latest"] as? String
hidden = event["hidden"] as? Bool
isStarred = event["is_starred"] as? Bool
hasPins = event["has_pins"] as? Bool
pinnedTo = event["pinned_top"] as? [String]
fileID = event["file_id"] as? String
presence = event["presence"] as? String
name = event["name"] as? String
value = event["value"]
plan = event["plan"] as? String
url = event["url"] as? String
domain = event["domain"] as? String
emailDomain = event["email_domain"] as? String
reaction = event["reaction"] as? String
replyTo = event["reply_to"] as? Double
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(dictionary: event)
nestedMessage = Message(dictionary: event["message"] as? [String: Any])
profile = CustomProfile(profile: event["profile"] as? [String: Any])
file = File(id: event["file"] as? String)
// Comment, Channel, and User can come across as Strings or Dictionaries
if let commentDictionary = event["comment"] as? [String: Any] {
comment = Comment(comment: commentDictionary)
} else {
comment = Comment(id: event["comment"] as? String)
}
if let userDictionary = event["user"] as? [String: Any] {
user = User(user: userDictionary)
} else {
user = User(id: event["user"] as? String)
}
if let channelDictionary = event["channel"] as? [String: Any] {
channel = Channel(channel: channelDictionary)
} else {
channel = Channel(id: event["channel"] as? String)
}
}
}
-109
View File
@@ -1,109 +0,0 @@
//
// EventDelegate.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 protocol ConnectionEventsDelegate: class {
func connected(_ client: Client)
func disconnected(_ client: Client)
func connectionFailed(_ client: Client, error: SlackError)
}
public protocol MessageEventsDelegate: class {
func sent(_ message: Message, client: Client)
func received(_ message: Message, client: Client)
func changed(_ message: Message, client: Client)
func deleted(_ message: Message?, client: Client)
}
public protocol ChannelEventsDelegate: class {
func userTypingIn(_ channel: Channel, user: User, client: Client)
func marked(_ channel: Channel, timestamp: String, client: Client)
func created(_ channel: Channel, client: Client)
func deleted(_ channel: Channel, client: Client)
func renamed(_ channel: Channel, client: Client)
func archived(_ channel: Channel, client: Client)
func historyChanged(_ channel: Channel, client: Client)
func joined(_ channel: Channel, client: Client)
func left(_ channel: Channel, client: Client)
}
public protocol DoNotDisturbEventsDelegate: class {
func updated(_ status: DoNotDisturbStatus, client: Client)
func userUpdated(_ status: DoNotDisturbStatus, user: User, client: Client)
}
public protocol GroupEventsDelegate: class {
func opened(_ group: Channel, client: Client)
}
public protocol FileEventsDelegate: class {
func processed(_ file: File, client: Client)
func madePrivate(_ file: File, client: Client)
func deleted(_ file: File, client: Client)
func commentAdded(_ file: File, comment: Comment, client: Client)
func commentEdited(_ file: File, comment: Comment, client: Client)
func commentDeleted(_ file: File, comment: Comment, client: Client)
}
public protocol PinEventsDelegate: class {
func pinned(_ item: Item, channel: Channel?, client: Client)
func unpinned(_ item: Item, channel: Channel?, client: Client)
}
public protocol StarEventsDelegate: class {
func starred(_ item: Item, starred: Bool, _ client: Client)
}
public protocol ReactionEventsDelegate: class {
func added(_ reaction: String, item: Item, itemUser: String, client: Client)
func removed(_ reaction: String, item: Item, itemUser: String, client: Client)
}
public protocol SlackEventsDelegate: class {
func preferenceChanged(_ preference: String, value: Any?, client: Client)
func userChanged(_ user: User, client: Client)
func presenceChanged(_ user: User, presence: String, client: Client)
func manualPresenceChanged(_ user: User, presence: String, client: Client)
func botEvent(_ bot: Bot, client: Client)
}
public protocol TeamEventsDelegate: class {
func userJoined(_ user: User, client: Client)
func planChanged(_ plan: String, client: Client)
func preferencesChanged(_ preference: String, value: Any?, client: Client)
func nameChanged(_ name: String, client: Client)
func domainChanged(_ domain: String, client: Client)
func emailDomainChanged(_ domain: String, client: Client)
func emojiChanged(_ client: Client)
}
public protocol SubteamEventsDelegate: class {
func event(_ userGroup: UserGroup, client: Client)
func selfAdded(_ subteamID: String, client: Client)
func selfRemoved(_ subteamID: String, client: Client)
}
public protocol TeamProfileEventsDelegate: class {
func changed(_ profile: CustomProfile, client: Client)
func deleted(_ profile: CustomProfile, client: Client)
func reordered(_ profile: CustomProfile, client: Client)
}
-57
View File
@@ -1,57 +0,0 @@
//
// Extensions.swift
//
// Copyright © 2016 Peter Zignego. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public extension Date {
var slackTimestamp: Double {
return NSNumber(value: timeIntervalSince1970).doubleValue
}
}
internal extension String {
var slackFormatEscaping: String {
var escapedString = replacingOccurrences(of: "&", with: "&amp;")
escapedString = replacingOccurrences(of: "<", with: "&lt;")
escapedString = replacingOccurrences(of: ">", with: "&gt;")
return escapedString
}
}
internal extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {
var requestStringFromParameters: String {
var requestString = ""
for key in self.keys {
if let value = self[key] as? String, let encodedValue = value.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed) {
requestString += "&\(key)=\(encodedValue)"
} else if let value = self[key] {
requestString += "&\(key)=\(value)"
}
}
return requestString
}
}
-186
View File
@@ -1,186 +0,0 @@
//
// File.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 File: Equatable {
public let id: String?
public let created: Int?
public let name: String?
public let title: String?
public let mimeType: String?
public let fileType: String?
public let prettyType: String?
public let user: String?
public let mode: String?
internal(set) public var editable: Bool?
public let isExternal: Bool?
public let externalType: String?
public let size: Int?
public let urlPrivate: String?
public let urlPrivateDownload: String?
public let thumb64: String?
public let thumb80: String?
public let thumb360: String?
public let thumb360gif: String?
public let thumb360w: String?
public let thumb360h: String?
public let thumb480: String?
public let thumb480gif: String?
public let thumb480w: String?
public let thumb480h: String?
public let thumb720: String?
public let thumb720gif: String?
public let thumb720w: String?
public let thumb720h: String?
public let thumb960: String?
public let thumb960gif: String?
public let thumb960w: String?
public let thumb960h: String?
public let thumb1024: String?
public let thumb1024gif: String?
public let thumb1024w: String?
public let thumb1024h: String?
public let permalink: String?
public let editLink: String?
public let preview: String?
public let previewHighlight: String?
public let lines: Int?
public let linesMore: Int?
internal(set) public var isPublic: Bool?
internal(set) public var publicSharedURL: Bool?
internal(set) public var channels: [String]?
internal(set) public var groups: [String]?
internal(set) public var ims: [String]?
public let initialComment: Comment?
internal(set) public var stars: Int?
internal(set) public var isStarred: Bool?
internal(set) public var pinnedTo: [String]?
internal(set) public var comments = [String: Comment]()
internal(set) public var reactions = [Reaction]()
public init(file:[String: Any]?) {
id = file?["id"] as? String
created = file?["created"] as? Int
name = file?["name"] as? String
title = file?["title"] as? String
mimeType = file?["mimetype"] as? String
fileType = file?["filetype"] as? String
prettyType = file?["pretty_type"] as? String
user = file?["user"] as? String
mode = file?["mode"] as? String
editable = file?["editable"] as? Bool
isExternal = file?["is_external"] as? Bool
externalType = file?["external_type"] as? String
size = file?["size"] as? Int
urlPrivate = file?["url_private"] as? String
urlPrivateDownload = file?["url_private_download"] as? String
thumb64 = file?["thumb_64"] as? String
thumb80 = file?["thumb_80"] as? String
thumb360 = file?["thumb_360"] as? String
thumb360gif = file?["thumb_360_gif"] as? String
thumb360w = file?["thumb_360_w"] as? String
thumb360h = file?["thumb_360_h"] as? String
thumb480 = file?["thumb_480"] as? String
thumb480gif = file?["thumb_480_gif"] as? String
thumb480w = file?["thumb_480_w"] as? String
thumb480h = file?["thumb_480_h"] as? String
thumb720 = file?["thumb_720"] as? String
thumb720gif = file?["thumb_720_gif"] as? String
thumb720w = file?["thumb_720_w"] as? String
thumb720h = file?["thumb_720_h"] as? String
thumb960 = file?["thumb_960"] as? String
thumb960gif = file?["thumb_960_gif"] as? String
thumb960w = file?["thumb_960_w"] as? String
thumb960h = file?["thumb_960_h"] as? String
thumb1024 = file?["thumb_1024"] as? String
thumb1024gif = file?["thumb_1024_gif"] as? String
thumb1024w = file?["thumb_1024_w"] as? String
thumb1024h = file?["thumb_1024_h"] as? String
permalink = file?["permalink"] as? String
editLink = file?["edit_link"] as? String
preview = file?["preview"] as? String
previewHighlight = file?["preview_highlight"] as? String
lines = file?["lines"] as? Int
linesMore = file?["lines_more"] as? Int
isPublic = file?["is_public"] as? Bool
publicSharedURL = file?["public_url_shared"] as? Bool
channels = file?["channels"] as? [String]
groups = file?["groups"] as? [String]
ims = file?["ims"] as? [String]
initialComment = Comment(comment: file?["initial_comment"] as? [String: Any])
stars = file?["num_stars"] as? Int
isStarred = file?["is_starred"] as? Bool
pinnedTo = file?["pinned_to"] as? [String]
reactions = Reaction.reactionsFromArray(file?["reactions"] as? [[String: Any]])
}
internal init(id:String?) {
self.id = id
created = nil
name = nil
title = nil
mimeType = nil
fileType = nil
prettyType = nil
user = nil
mode = nil
isExternal = nil
externalType = nil
size = nil
urlPrivate = nil
urlPrivateDownload = nil
thumb64 = nil
thumb80 = nil
thumb360 = nil
thumb360gif = nil
thumb360w = nil
thumb360h = nil
thumb480 = nil
thumb480gif = nil
thumb480w = nil
thumb480h = nil
thumb720 = nil
thumb720gif = nil
thumb720w = nil
thumb720h = nil
thumb960 = nil
thumb960gif = nil
thumb960w = nil
thumb960h = nil
thumb1024 = nil
thumb1024gif = nil
thumb1024w = nil
thumb1024h = nil
permalink = nil
editLink = nil
preview = nil
previewHighlight = nil
lines = nil
linesMore = nil
initialComment = nil
}
public static func ==(lhs: File, rhs: File) -> Bool {
return lhs.id == rhs.id
}
}
-43
View File
@@ -1,43 +0,0 @@
//
// History.swift
//
// Copyright © 2016 Peter Zignego. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public struct History {
internal(set) public var latest: Date?
internal(set) public var messages = [Message]()
public let hasMore: Bool?
internal init(history: [String: Any]?) {
if let latestStr = history?["latest"] as? String, let latestDouble = Double(latestStr) {
latest = Date(timeIntervalSince1970: TimeInterval(latestDouble))
}
if let msgs = history?["messages"] as? [[String: Any]] {
for message in msgs {
messages.append(Message(dictionary: message))
}
}
hasMore = history?["has_more"] as? Bool
}
}
-71
View File
@@ -1,71 +0,0 @@
//
// IncomingWebhook.swift
//
// Copyright © 2016 Peter Zignego. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public struct IncomingWebhook {
public let url: String?
public let channel: String?
public let configurationURL: String?
public let username: String?
public let iconEmoji: String?
public let iconURL: String?
internal init(webhook: [String: Any]?) {
url = webhook?["url"] as? String
channel = webhook?["channel"] as? String
configurationURL = webhook?["configuration_url"] as? String
username = webhook?["username"] as? String
iconEmoji = webhook?["icon_emoji"] as? String
iconURL = webhook?["icon_url"] as? String
}
public init(url: String, channel: String? = nil, username: String? = nil, iconEmoji: String? = nil, iconURL: String? = nil) {
self.url = url
self.channel = channel
self.username = username
self.iconEmoji = iconEmoji
self.iconURL = iconURL
self.configurationURL = nil
}
public func postMessage(_ response: Response, success: ((Bool)->Void)? = nil, failure: ((SlackError)->Void)? = nil) {
if let url = self.url, let data = try? JSONSerialization.data(withJSONObject: jsonBody(response.json), options: []) {
NetworkInterface().customRequest(url, data: data, success: { _ in
success?(true)
}, errorClosure: {(error) in
failure?(error)
})
}
}
private func jsonBody(_ response: [String: Any]) -> [String: Any] {
var json = response
json["channel"] = channel
json["username"] = username
json["icon_emoji"] = iconEmoji
json["icon_url"] = iconURL
return json
}
}
-59
View File
@@ -1,59 +0,0 @@
//
// Item.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 Item: Equatable {
public let type: String?
public let ts: String?
public let channel: String?
public let message: Message?
public let file: File?
public let comment: Comment?
public let fileCommentID: String?
internal init(item:[String: Any]?) {
type = item?["type"] as? String
ts = item?["ts"] as? String
channel = item?["channel"] as? String
message = Message(dictionary: item?["message"] as? [String: Any])
// Comment and File can come across as Strings or Dictionaries
if let commentDictionary = item?["comment"] as? [String: Any] {
comment = Comment(comment: commentDictionary)
} else {
comment = Comment(id: item?["comment"] as? String)
}
if let fileDictionary = item?["file"] as? [String: Any] {
file = File(file: fileDictionary)
} else {
file = File(id: item?["file"] as? String)
}
fileCommentID = item?["file_comment"] as? String
}
public static func ==(lhs: Item, rhs: Item) -> Bool {
return lhs.type == rhs.type && lhs.channel == rhs.channel && lhs.file == rhs.file && lhs.comment == rhs.comment && lhs.message == rhs.message
}
}
-101
View File
@@ -1,101 +0,0 @@
//
// Message.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 final class Message: Equatable {
public let type = "message"
public let subtype: String?
internal(set) public var ts: String?
public let user: String?
public let channel: String?
internal(set) public var hidden: Bool?
internal(set) public var text: String?
public let botID: String?
public let username: String?
public let icons: [String: Any]?
public let deletedTs: String?
internal(set) var purpose: String?
internal(set) var topic: String?
internal(set) var name: String?
internal(set) var members: [String]?
internal(set) var oldName: String?
public let upload: Bool?
public let itemType: String?
internal(set) public var isStarred: Bool?
internal(set) var pinnedTo: [String]?
public let comment: Comment?
public let file: File?
internal(set) public var reactions = [Reaction]()
internal(set) public var attachments: [Attachment]?
internal(set) public var responseType: ResponseType?
internal(set) public var replaceOriginal: Bool?
internal(set) public var deleteOriginal: Bool?
public init(dictionary: [String: Any]?) {
subtype = dictionary?["subtype"] as? String
ts = dictionary?["ts"] as? String
user = dictionary?["user"] as? String
channel = dictionary?["channel"] as? String
hidden = dictionary?["hidden"] as? Bool
text = dictionary?["text"] as? String
botID = dictionary?["bot_id"] as? String
username = dictionary?["username"] as? String
icons = dictionary?["icons"] as? [String: Any]
deletedTs = dictionary?["deleted_ts"] as? String
purpose = dictionary?["purpose"] as? String
topic = dictionary?["topic"] as? String
name = dictionary?["name"] as? String
members = dictionary?["members"] as? [String]
oldName = dictionary?["old_name"] as? String
upload = dictionary?["upload"] as? Bool
itemType = dictionary?["item_type"] as? String
isStarred = dictionary?["is_starred"] as? Bool
pinnedTo = dictionary?["pinned_to"] as? [String]
comment = Comment(comment: dictionary?["comment"] as? [String: Any])
file = File(file: dictionary?["file"] as? [String: Any])
reactions = Reaction.reactionsFromArray(dictionary?["reactions"] as? [[String: Any]])
attachments = (dictionary?["attachments"] as? [[String: Any]])?.map{Attachment(attachment: $0)}
responseType = ResponseType(rawValue: dictionary?["response_type"] as? String ?? "")
replaceOriginal = dictionary?["replace_original"] as? Bool
deleteOriginal = dictionary?["delete_original"] as? Bool
}
internal init(ts:String?) {
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
}
public static func ==(lhs: Message, rhs: Message) -> Bool {
return lhs.ts == rhs.ts && lhs.user == rhs.user && lhs.text == rhs.text
}
}
@@ -1,51 +0,0 @@
//
// MessageActionRequest.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.
internal struct MessageActionRequest: Request {
let action: Action?
let callbackID: String?
let team: Team?
let channel: Channel?
let user: User?
let actionTS: String?
let messageTS: String?
let attachmentID: String?
let token: String?
let originalMessage: Message?
let responseURL: String
init(response: [String: Any]?) {
action = (response?["actions"] as? [[String:Any]])?.map({Action(action: $0)}).first
callbackID = response?["callback_id"] as? String
team = Team(team: response?["team"] as? [String: Any])
channel = Channel(channel: response?["channel"] as? [String: Any])
user = User(user: response?["channel"] as? [String: Any])
actionTS = response?["action_ts"] as? String
messageTS = response?["message_ts"] as? String
attachmentID = response?["attachment_id"] as? String
token = response?["token"] as? String
originalMessage = Message(dictionary: response?["original_message"] as? [String: Any])
responseURL = response?["response_url"] as? String ?? ""
}
}
@@ -1,39 +0,0 @@
//
// MessageActionResponder.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 MessageActionResponder {
public var responses:[(Action, Response)]
public init(responses:[(Action, Response)]) {
self.responses = responses
}
internal func responseForRequest(_ request:MessageActionRequest) -> Reply? {
if let response = responses.filter({$0.0.name == request.action?.name}).first?.1 {
return Reply.json(response: response)
} else {
return nil
}
}
}
@@ -1,45 +0,0 @@
//
// MessageActionServer.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.
open class MessageActionServer: Server {
internal let responder: MessageActionResponder
required public init(token: String, route: String, responder: MessageActionResponder) {
self.responder = responder
super.init(token: token)
addRoute(route)
}
internal func addRoute(_ route: String) {
http.POST["/\(route)"] = { request in
let payload = request.parseUrlencodedForm()
let actionRequest = MessageActionRequest(response: self.jsonFromRequest(payload[0].1))
if let reply = self.responder.responseForRequest(actionRequest), actionRequest.token == self.token {
return self.request(actionRequest, reply: reply)
} else {
return .badRequest(.text("Bad request."))
}
}
}
}
-148
View File
@@ -1,148 +0,0 @@
//
// NetworkInterface.swift
//
// Copyright © 2016 Peter Zignego. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
internal struct NetworkInterface {
private let apiUrl = "https://slack.com/api/"
internal func request(_ endpoint: Endpoint, token: String? = nil, parameters: [String: Any]?, successClosure: @escaping ([String: Any])->Void, errorClosure: @escaping (SlackError)->Void) {
var requestString = "\(apiUrl)\(endpoint.rawValue)?"
if let token = token {
requestString += "token=\(token)"
}
if let params = parameters {
requestString += params.requestStringFromParameters
}
guard let url = URL(string: requestString) else {
errorClosure(SlackError.clientNetworkError)
return
}
let request = URLRequest(url:url)
URLSession.shared.dataTask(with: request) {(data, response, internalError) in
do {
successClosure(try self.handleResponse(data, response: response, internalError: internalError))
} catch let error {
errorClosure(error as? SlackError ?? SlackError.unknownError)
}
}.resume()
}
internal func customRequest(_ url: String, data: Data, success: @escaping (Bool)->Void, errorClosure: @escaping (SlackError)->Void) {
guard let url = URL(string: url.removePercentEncoding()) else {
errorClosure(SlackError.clientNetworkError)
return
}
var request = URLRequest(url:url)
request.httpMethod = "POST"
let contentType = "application/json"
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
request.httpBody = data
URLSession.shared.dataTask(with: request) {(data, response, internalError) in
if internalError == nil {
success(true)
} else {
errorClosure(SlackError.clientNetworkError)
}
}.resume()
}
internal func uploadRequest(_ token: String, data: Data, parameters: [String: Any]?, successClosure: @escaping ([String: Any])->Void, errorClosure: @escaping (SlackError)->Void) {
var requestString = "\(apiUrl)\(Endpoint.filesUpload.rawValue)?token=\(token)"
if let params = parameters {
requestString = requestString + params.requestStringFromParameters
}
guard let url = URL(string: requestString) else {
errorClosure(SlackError.clientNetworkError)
return
}
var request = URLRequest(url:url)
request.httpMethod = "POST"
let boundaryConstant = randomBoundary()
let contentType = "multipart/form-data; boundary=" + boundaryConstant
let boundaryStart = "--\(boundaryConstant)\r\n"
let boundaryEnd = "--\(boundaryConstant)--\r\n"
let contentDispositionString = "Content-Disposition: form-data; name=\"file\"; filename=\"\(parameters!["filename"])\"\r\n"
let contentTypeString = "Content-Type: \(parameters!["filetype"])\r\n\r\n"
var requestBodyData: Data = Data()
requestBodyData.append(boundaryStart.data(using: String.Encoding.utf8)!)
requestBodyData.append(contentDispositionString.data(using: String.Encoding.utf8)!)
requestBodyData.append(contentTypeString.data(using: String.Encoding.utf8)!)
requestBodyData.append(data)
requestBodyData.append("\r\n".data(using: String.Encoding.utf8)!)
requestBodyData.append(boundaryEnd.data(using: String.Encoding.utf8)!)
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
request.httpBody = requestBodyData as Data
URLSession.shared.dataTask(with: request) {(data, response, internalError) in
do {
successClosure(try self.handleResponse(data, response: response, internalError: internalError))
} catch let error {
errorClosure(error as? SlackError ?? SlackError.unknownError)
}
}.resume()
}
private func handleResponse(_ data: Data?, response:URLResponse?, internalError:Error?) throws -> [String: Any] {
guard let data = data, let response = response as? HTTPURLResponse else {
throw SlackError.clientNetworkError
}
do {
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
throw SlackError.clientJSONError
}
switch response.statusCode {
case 200:
if (json["ok"] as! Bool == true) {
return json
} else {
if let errorString = json["error"] as? String {
throw SlackError(rawValue: errorString) ?? .unknownError
} else {
throw SlackError.unknownError
}
}
case 429:
throw SlackError.tooManyRequests
default:
throw SlackError.clientNetworkError
}
} catch let error {
if let slackError = error as? SlackError {
throw slackError
} else {
throw SlackError.unknownError
}
}
}
private func randomBoundary() -> String {
return String(format: "slackkit.boundary.%08x%08x", arc4random(), arc4random())
}
}
-44
View File
@@ -1,44 +0,0 @@
//
// OAuthResponse.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.
internal struct OAuthResponse {
let accessToken: String?
let scope: [Scope]?
let userID: String?
let teamName: String?
let teamID: String?
let incomingWebhook: IncomingWebhook?
let bot: Bot?
init(response: [String: Any]?) {
accessToken = response?["access_token"] as? String
scope = (response?["scope"] as? String)?.components(separatedBy: ",").flatMap{Scope(rawValue:$0)}
userID = response?["user_id"] as? String
teamName = response?["team_name"] as? String
teamID = response?["team_id"] as? String
incomingWebhook = IncomingWebhook(webhook: response?["incoming_webhook"] as? [String: Any])
bot = Bot(botUser: response?["bot"] as? [String: Any])
}
}
-94
View File
@@ -1,94 +0,0 @@
//
// OAuthServer.swift
//
// Copyright © 2016 Peter Zignego. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Swifter
internal protocol OAuthDelegate {
func userAuthed(_ response: OAuthResponse)
}
public struct OAuthServer {
private let oauthURL = "https://slack.com/oauth/authorize"
private let http = HttpServer()
private let clientID: String
private let clientSecret: String
private let state: String?
private let redirectURI: String?
private var delegate: OAuthDelegate?
internal init(clientID: String, clientSecret: String, state: String? = nil, redirectURI: String? = nil, port:in_port_t = 8080, forceIPV4: Bool = false, delegate: OAuthDelegate? = nil) throws {
self.clientID = clientID
self.clientSecret = clientSecret
self.state = state ?? "state"
self.redirectURI = redirectURI
self.delegate = delegate
oauthRoute()
start(port, forceIPV4: forceIPV4)
}
public func start(_ port: in_port_t = 8080, forceIPV4: Bool = false) {
do {
try http.start(port, forceIPv4: forceIPV4)
} catch let error as NSError {
print("Server failed to start with error: \(error)")
}
}
public func stop() {
http.stop()
}
private func oauthRoute() {
http["/oauth"] = { request in
guard let response = AuthorizeResponse(queryParameters: request.queryParams), response.state == self.state else {
return .badRequest(.text("Bad request."))
}
WebAPI.oauthAccess(self.clientID, clientSecret: self.clientSecret, code: response.code, redirectURI: self.redirectURI, success: {(response) in
self.delegate?.userAuthed(OAuthResponse(response: response))
}, failure: {(error) in
print("Authorization failed")
})
if let redirect = self.redirectURI {
return .movedPermanently(redirect)
}
return .ok(.text("Authentication successful."))
}
}
private func oauthURLRequest(_ authorize: AuthorizeRequest) -> URLRequest? {
var requestString = "\(oauthURL)?client_id=\(authorize.clientID)"
requestString += authorize.parameters.requestStringFromParameters
guard let url = URL(string: requestString) else {
return nil
}
return URLRequest(url:url)
}
public func authorizeRequest(_ scope:[Scope], redirectURI: String, state: String = "slackkit", team: String? = nil) -> URLRequest? {
let request = AuthorizeRequest(clientID: clientID, scope: scope, redirectURI: redirectURI, state: state, team: team)
return oauthURLRequest(request)
}
}
-55
View File
@@ -1,55 +0,0 @@
//
// Reaction.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 Reaction: Equatable {
public let name: String?
internal(set) public var user: String?
internal init(reaction:[String: Any]?) {
name = reaction?["name"] as? String
}
internal init(name: String, user: String) {
self.name = name
self.user = user
}
static func reactionsFromArray(_ array: [[String: Any]]?) -> [Reaction] {
var reactions = [Reaction]()
if let array = array {
for reaction in array {
if let users = reaction["users"] as? [String], let name = reaction["name"] as? String {
for user in users {
reactions.append(Reaction(name: name, user: user))
}
}
}
}
return reactions
}
public static func ==(lhs: Reaction, rhs: Reaction) -> Bool {
return lhs.name == rhs.name
}
}
-43
View File
@@ -1,43 +0,0 @@
//
// Response.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 Response {
let text: String
let responseType: ResponseType?
let attachments: [Attachment]?
public init(text: String, responseType: ResponseType? = nil, attachments: [Attachment]? = nil) {
self.responseType = responseType
self.text = text
self.attachments = attachments
}
internal var json: [String: Any] {
var json = [String : Any]()
json["text"] = text
json["response_type"] = responseType?.rawValue
json["attachments"] = attachments?.map({$0.dictionary})
return json
}
}
-71
View File
@@ -1,71 +0,0 @@
//
// Scope.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 enum Scope: String {
case ChannelsHistory = "channels:history"
case ChannelsRead = "channels:read"
case ChannelsWrite = "channels:write"
case ChatWriteBot = "chat:write:bot"
case ChatWriteUser = "chat:write:user"
case DNDRead = "dnd:read"
case DNDWrite = "dnd:write"
case EmojiRead = "emoji:read"
case FilesRead = "files:read"
case FilesWriteUser = "files:write:user"
case GroupsHistory = "groups:history"
case GroupsRead = "groups:read"
case GroupsWrite = "groups:write"
case IdentityBasic = "identity.basic"
case IMHistory = "im:history"
case IMRead = "im:read"
case IMWrite = "im:write"
case MPIMHistory = "mpim:history"
case MPIMRead = "mpim:read"
case MPIMWrite = "mpim:write"
case PinsRead = "pins:read"
case PinsWrite = "pins:write"
case ReactionsRead = "reactions:read"
case ReactionsWrite = "reactions:write"
case RemindersRead = "reminders:read"
case RemindersWrite = "reminders:write"
case SearchRead = "search:read"
case StarsRead = "stars:read"
case StarsWrite = "stars:write"
case TeamRead = "team:read"
case UserGroupsRead = "usergroups:read"
case UserGroupsWrite = "usergroups:write"
case UserProfilesRead = "user.profiles:read"
case UserProfilesWrite = "user.profiles:write"
case UsersRead = "users:read"
case UsersWrite = "users:write"
case IncomingWebhook = "incoming-webhook"
case Commands = "commands"
case Bot = "bot"
case Identify = "identify"
case Client = "client"
case Admin = "admin"
//Deprecated
case Read = "read"
case Post = "post"
}
-90
View File
@@ -1,90 +0,0 @@
//
// Server.swift
//
// Copyright © 2016 Peter Zignego. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Swifter
internal enum Reply {
case json(response: Response)
case text(body: String)
case badRequest
}
internal protocol Request {
var responseURL: String { get }
}
open class Server {
internal let http = HttpServer()
internal let token: String
internal init(token: String) {
self.token = token
}
open func start(_ port: in_port_t = 8080, forceIPV4: Bool = false) {
do {
try http.start(port, forceIPv4: forceIPV4)
} catch let error as NSError {
print("Server failed to start with error: \(error)")
}
}
open func stop() {
http.stop()
}
internal func request(_ request:Request, reply: Reply) -> HttpResponse {
switch reply {
case .text(let body):
return .ok(.text(body))
case .json(let response):
return .ok(.json(response.json as AnyObject))
case .badRequest:
return .badRequest(.text("Bad request."))
}
}
internal func dictionaryFromRequest(_ body: [UInt8]) -> [String: Any]? {
let string = String(data: Data(bytes: UnsafePointer<UInt8>(body), count: body.count), encoding: String.Encoding.utf8)
if let body = string?.components(separatedBy: "&") {
var dict: [String: Any] = [:]
for argument in body {
let kv = argument.components(separatedBy: "=")
if let key = kv.first, let value = kv.last {
dict[key] = value as Any?
}
}
return dict
}
return nil
}
internal func jsonFromRequest(_ string: String) -> [String: Any]? {
guard let data = string.data(using: String.Encoding.utf8) else {
return nil
}
return (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] ?? nil
}
}
-121
View File
@@ -1,121 +0,0 @@
//
// SlackError.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 enum SlackError: String, Error {
case accountInactive = "account_inactive"
case alreadyArchived = "already_archived"
case alreadyInChannel = "already_in_channel"
case alreadyPinned = "already_pinned"
case alreadyReacted = "already_reacted"
case alreadyStarred = "already_starred"
case badClientSecret = "bad_client_secret"
case badRedirectURI = "bad_redirect_uri"
case badTimeStamp = "bad_timestamp"
case cantArchiveGeneral = "cant_archive_general"
case cantDelete = "cant_delete"
case cantDeleteFile = "cant_delete_file"
case cantDeleteMessage = "cant_delete_message"
case cantInvite = "cant_invite"
case cantInviteSelf = "cant_invite_self"
case cantKickFromGeneral = "cant_kick_from_general"
case cantKickFromLastChannel = "cant_kick_from_last_channel"
case cantKickSelf = "cant_kick_self"
case cantLeaveGeneral = "cant_leave_general"
case cantLeaveLastChannel = "cant_leave_last_channel"
case cantUpdateMessage = "cant_update_message"
case channelNotFound = "channel_not_found"
case complianceExportsPreventDeletion = "compliance_exports_prevent_deletion"
case editWindowClosed = "edit_window_closed"
case fileCommentNotFound = "file_comment_not_found"
case fileDeleted = "file_deleted"
case fileNotFound = "file_not_found"
case fileNotShared = "file_not_shared"
case groupContainsOthers = "group_contains_others"
case invalidArgName = "invalid_arg_name"
case invalidArrayArg = "invalid_array_arg"
case invalidAuth = "invalid_auth"
case invalidChannel = "invalid_channel"
case invalidCharSet = "invalid_charset"
case invalidClientID = "invalid_client_id"
case invalidCode = "invalid_code"
case invalidFormData = "invalid_form_data"
case invalidName = "invalid_name"
case invalidPostType = "invalid_post_type"
case invalidPresence = "invalid_presence"
case invalidTS = "invalid_timestamp"
case invalidTSLatest = "invalid_ts_latest"
case invalidTSOldest = "invalid_ts_oldest"
case isArchived = "is_archived"
case lastMember = "last_member"
case lastRAChannel = "last_ra_channel"
case messageNotFound = "message_not_found"
case messageTooLong = "msg_too_long"
case migrationInProgress = "migration_in_progress"
case missingDuration = "missing_duration"
case missingPostType = "missing_post_type"
case missingScope = "missing_scope"
case nameTaken = "name_taken"
case noChannel = "no_channel"
case noComment = "no_comment"
case noItemSpecified = "no_item_specified"
case noReaction = "no_reaction"
case noText = "no_text"
case notArchived = "not_archived"
case notAuthed = "not_authed"
case notEnoughUsers = "not_enough_users"
case notInChannel = "not_in_channel"
case notInGroup = "not_in_group"
case notPinned = "not_pinned"
case notStarred = "not_starred"
case overPaginationLimit = "over_pagination_limit"
case paidOnly = "paid_only"
case permissionDenied = "perimssion_denied"
case postingToGeneralChannelDenied = "posting_to_general_channel_denied"
case rateLimited = "rate_limited"
case requestTimeout = "request_timeout"
case restrictedAction = "restricted_action"
case snoozeEndFailed = "snooze_end_failed"
case snoozeFailed = "snooze_failed"
case snoozeNotActive = "snooze_not_active"
case tooLong = "too_long"
case tooManyEmoji = "too_many_emoji"
case tooManyReactions = "too_many_reactions"
case tooManyUsers = "too_many_users"
case unknownError
case unknownType = "unknown_type"
case userDisabled = "user_disabled"
case userDoesNotOwnChannel = "user_does_not_own_channel"
case userIsBot = "user_is_bot"
case userIsRestricted = "user_is_restricted"
case userIsUltraRestricted = "user_is_ultra_restricted"
case userListNotSupplied = "user_list_not_supplied"
case userNotFound = "user_not_found"
case userNotVisible = "user_not_visible"
// Client
case clientNetworkError
case clientJSONError
case clientOAuthError
// HTTP
case tooManyRequests
case unknownHTTPError
}
-66
View File
@@ -1,66 +0,0 @@
//
// SlackKit.swift
//
// Copyright © 2016 Peter Zignego. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public final class SlackKit: OAuthDelegate {
internal(set) public var oauth: OAuthServer?
internal(set) public var clients: [String: Client] = [:]
private let clientOptions: ClientOptions
// Initalization block
public var onClientInitalization: ((Client) -> Void)?
// If you already have an API token
public init(withAPIToken token: String, clientOptions: ClientOptions = ClientOptions()) {
self.clientOptions = clientOptions
let client = Client(apiToken: token)
DispatchQueue.main.async(execute: {
self.onClientInitalization?(client)
})
clients[token] = client
client.connect(options: self.clientOptions)
}
// If you're going to be receiving and/or initiating OAuth requests, provide a client ID and secret
public init(clientID: String, clientSecret: String, state: String? = nil, redirectURI: String? = nil, port:in_port_t = 8080, forceIPV4: Bool = false, clientOptions: ClientOptions = ClientOptions()) {
self.clientOptions = clientOptions
oauth = try? OAuthServer(clientID: clientID, clientSecret: clientSecret, state: state, redirectURI: redirectURI, port: port, forceIPV4: forceIPV4, delegate: self)
}
internal func userAuthed(_ response: OAuthResponse) {
// User auth
if let token = response.accessToken {
let client = Client(apiToken: token)
self.onClientInitalization?(client)
clients[token] = client
}
// Bot User
if let token = response.bot?.botToken {
let client = Client(apiToken: token)
self.onClientInitalization?(client)
clients[token] = client
client.connect(options: self.clientOptions)
}
}
}
-47
View File
@@ -1,47 +0,0 @@
//
// Team.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 Team {
public let id: String?
internal(set) public var name: 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: Any]?
internal(set) public var plan: String?
internal(set) public var icon: TeamIcon?
internal init(team: [String: Any]?) {
id = team?["id"] as? String
name = team?["name"] as? String
domain = team?["domain"] as? String
emailDomain = team?["email_domain"] as? String
messageEditWindowMinutes = team?["msg_edit_window_mins"] as? Int
overStorageLimit = team?["over_storage_limit"] as? Bool
prefs = team?["prefs"] as? [String: Any]
plan = team?["plan"] as? String
icon = TeamIcon(icon: team?["icon"] as? [String: Any])
}
}
-45
View File
@@ -1,45 +0,0 @@
//
// TeamIcon.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 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
}
}
-35
View File
@@ -1,35 +0,0 @@
//
// Topic.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 Topic {
public let value: String?
public let creator: String?
public let lastSet: Int?
internal init(topic: [String: Any]?) {
value = topic?["value"] as? String
creator = topic?["creator"] as? String
lastSet = topic?["last_set"] as? Int
}
}
-106
View File
@@ -1,106 +0,0 @@
//
// User.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 User {
public struct Profile {
internal(set) public var firstName: String?
internal(set) public var lastName: String?
internal(set) public var realName: String?
internal(set) public var email: String?
internal(set) public var skype: String?
internal(set) public var phone: String?
internal(set) public var image24: String?
internal(set) public var image32: String?
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: Any]?) {
firstName = profile?["first_name"] as? String
lastName = profile?["last_name"] as? String
realName = profile?["real_name"] as? String
email = profile?["email"] as? String
skype = profile?["skype"] as? String
phone = profile?["phone"] as? String
image24 = profile?["image_24"] as? String
image32 = profile?["image_32"] as? String
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?
internal(set) public var profile: Profile?
internal(set) public var doNotDisturbStatus: DoNotDisturbStatus?
internal(set) public var presence: String?
internal(set) public var color: String?
public let isBot: Bool?
internal(set) public var isAdmin: Bool?
internal(set) public var isOwner: Bool?
internal(set) public var isPrimaryOwner: Bool?
internal(set) public var isRestricted: Bool?
internal(set) public var isUltraRestricted: Bool?
internal(set) public var has2fa: Bool?
internal(set) public var hasFiles: Bool?
internal(set) public var status: String?
internal(set) public var timeZone: String?
internal(set) public var timeZoneLabel: String?
internal(set) public var timeZoneOffSet: Int?
internal(set) public var preferences: [String: Any]?
// Client properties
internal(set) public var userGroups: [String: String]?
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: Any])
color = user?["color"] as? String
isAdmin = user?["is_admin"] as? Bool
isOwner = user?["is_owner"] as? Bool
isPrimaryOwner = user?["is_primary_owner"] as? Bool
isRestricted = user?["is_restricted"] as? Bool
isUltraRestricted = user?["is_ultra_restricted"] as? Bool
has2fa = user?["has_2fa"] as? Bool
hasFiles = user?["has_files"] as? Bool
isBot = user?["is_bot"] as? Bool
presence = user?["presence"] as? String
status = user?["status"] as? String
timeZone = user?["tz"] as? String
timeZoneLabel = user?["tz_label"] as? String
timeZoneOffSet = user?["tz_offset"] as? Int
preferences = user?["prefs"] as? [String: Any]
}
internal init(id: String?) {
self.id = id
self.isBot = nil
}
}
-65
View File
@@ -1,65 +0,0 @@
//
// UserGroup.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 UserGroup {
public let id: String?
internal(set) public var teamID: String?
public let isUserGroup: Bool?
internal(set) public var name: String?
internal(set) public var description: String?
internal(set) public var handle: String?
internal(set) public var isExternal: Bool?
public let dateCreated: Int?
internal(set) public var dateUpdated: Int?
internal(set) public var dateDeleted: Int?
internal(set) public var autoType: String?
public let createdBy: String?
internal(set) public var updatedBy: String?
internal(set) public var deletedBy: String?
internal(set) public var preferences: [String: Any]?
internal(set) public var users: [String]?
internal(set) public var userCount: Int?
internal init(userGroup: [String: Any]?) {
id = userGroup?["id"] as? String
teamID = userGroup?["team_id"] as? String
isUserGroup = userGroup?["is_usergroup"] as? Bool
name = userGroup?["name"] as? String
description = userGroup?["description"] as? String
handle = userGroup?["handle"] as? String
isExternal = userGroup?["is_external"] as? Bool
dateCreated = userGroup?["date_create"] as? Int
dateUpdated = userGroup?["date_update"] as? Int
dateDeleted = userGroup?["date_delete"] as? Int
autoType = userGroup?["auto_type"] as? String
createdBy = userGroup?["created_by"] as? String
updatedBy = userGroup?["updated_by"] as? String
deletedBy = userGroup?["deleted_by"] as? String
preferences = userGroup?["prefs"] as? [String: Any]
users = userGroup?["users"] as? [String]
if let count = userGroup?["user_count"] as? String {
userCount = Int(count)
}
}
}
-719
View File
@@ -1,719 +0,0 @@
//
// WebAPI.swift
//
// Copyright © 2016 Peter Zignego. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
internal enum Endpoint: String {
case apiTest = "api.test"
case authRevoke = "auth.revoke"
case authTest = "auth.test"
case channelsHistory = "channels.history"
case channelsInfo = "channels.info"
case channelsList = "channels.list"
case channelsMark = "channels.mark"
case channelsSetPurpose = "channels.setPurpose"
case channelsSetTopic = "channels.setTopic"
case chatDelete = "chat.delete"
case chatPostMessage = "chat.postMessage"
case chatMeMessage = "chat.meMessage"
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 filesInfo = "files.info"
case filesUpload = "files.upload"
case groupsClose = "groups.close"
case groupsHistory = "groups.history"
case groupsInfo = "groups.info"
case groupsList = "groups.list"
case groupsMark = "groups.mark"
case groupsOpen = "groups.open"
case groupsSetPurpose = "groups.setPurpose"
case groupsSetTopic = "groups.setTopic"
case imClose = "im.close"
case imHistory = "im.history"
case imList = "im.list"
case imMark = "im.mark"
case imOpen = "im.open"
case mpimClose = "mpim.close"
case mpimHistory = "mpim.history"
case mpimList = "mpim.list"
case mpimMark = "mpim.mark"
case mpimOpen = "mpim.open"
case oauthAccess = "oauth.access"
case pinsAdd = "pins.add"
case pinsRemove = "pins.remove"
case reactionsAdd = "reactions.add"
case reactionsGet = "reactions.get"
case reactionsList = "reactions.list"
case reactionsRemove = "reactions.remove"
case rtmStart = "rtm.start"
case starsAdd = "stars.add"
case starsRemove = "stars.remove"
case teamInfo = "team.info"
case usersGetPresence = "users.getPresence"
case usersInfo = "users.info"
case usersList = "users.list"
case usersSetActive = "users.setActive"
case usersSetPresence = "users.setPresence"
}
public final class WebAPI {
public typealias FailureClosure = (_ error: SlackError)->Void
public enum InfoType: String {
case purpose = "purpose"
case topic = "topic"
}
public enum ParseMode: String {
case full = "full"
case none = "none"
}
public enum Presence: String {
case auto = "auto"
case away = "away"
}
private enum ChannelType: String {
case channel = "channel"
case group = "group"
case im = "im"
}
private let networkInterface: NetworkInterface
private let token: String
public init(token: String) {
self.networkInterface = NetworkInterface()
self.token = token
}
//MARK: - RTM
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]
networkInterface.request(.rtmStart, token: token, parameters: WebAPI.filterNilParameters(parameters), successClosure: {(response) in
success?(response)
}) {(error) in
failure?(error)
}
}
//MARK: - Auth
public func authenticationTest(_ success: ((_ authenticated: Bool)->Void)?, failure: FailureClosure?) {
networkInterface.request(.authTest, token: token, parameters: nil, successClosure: {(response) in
success?(true)
}) {(error) in
failure?(error)
}
}
public static func oauthAccess(_ clientID: String, clientSecret: String, code: String, redirectURI: String? = nil, success: ((_ response: [String: Any])->Void)?, failure: ((SlackError)->Void)?) {
let parameters: [String: Any?] = ["client_id": clientID, "client_secret": clientSecret, "code": code, "redirect_uri": redirectURI]
NetworkInterface().request(.oauthAccess, parameters: filterNilParameters(parameters), successClosure: {(response) in
success?(response)
}) {(error) in
failure?(error)
}
}
public static func oauthRevoke(_ token: String, test: Bool? = nil, success: ((_ revoked:Bool)->Void)?, failure: ((SlackError)->Void)?) {
let parameters: [String: Any?] = ["token": token, "test": test]
NetworkInterface().request(.authRevoke, parameters: filterNilParameters(parameters), successClosure: {(response) in
success?(true)
}) {(error) in
failure?(error)
}
}
//MARK: - Channels
public func channelHistory(_ id: String, latest: String = "\(Date().timeIntervalSince1970)", oldest: String = "0", inclusive: Bool = false, count: Int = 100, unreads: Bool = false, success: ((_ history: History)->Void)?, failure: FailureClosure?) {
history(.channelsHistory, id: id, latest: latest, oldest: oldest, inclusive: inclusive, count: count, unreads: unreads, success: {(history) in
success?(history)
}) {(error) in
failure?(error)
}
}
public func channelInfo(_ id: String, success: ((_ channel: Channel)->Void)?, failure: FailureClosure?) {
info(.channelsInfo, type:.channel, id: id, success: {(channel) in
success?(channel)
}) {(error) in
failure?(error)
}
}
public func channelsList(_ excludeArchived: Bool = false, success: ((_ channels: [[String: Any]]?)->Void)?, failure: FailureClosure?) {
list(.channelsList, type:.channel, excludeArchived: excludeArchived, success: {(channels) in
success?(channels)
}) {(error) in
failure?(error)
}
}
public func markChannel(_ channel: String, timestamp: String, success: ((_ ts: String)->Void)?, failure: FailureClosure?) {
mark(.channelsMark, channel: channel, timestamp: timestamp, success: {(ts) in
success?(timestamp)
}) {(error) in
failure?(error)
}
}
public func setChannelPurpose(_ channel: String, purpose: String, success: ((_ purposeSet: Bool)->Void)?, failure: FailureClosure?) {
setInfo(.channelsSetPurpose, type: .purpose, channel: channel, text: purpose, success: {(purposeSet) in
success?(purposeSet)
}) {(error) in
failure?(error)
}
}
public func setChannelTopic(_ channel: String, topic: String, success: ((_ topicSet: Bool)->Void)?, failure: FailureClosure?) {
setInfo(.channelsSetTopic, type: .topic, channel: channel, text: topic, success: {(topicSet) in
success?(topicSet)
}) {(error) in
failure?(error)
}
}
//MARK: - Messaging
public func deleteMessage(_ channel: String, ts: String, success: ((_ deleted: Bool)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any] = ["channel": channel, "ts": ts]
networkInterface.request(.chatDelete, token: token, parameters: parameters, successClosure: {(response) in
success?(true)
}) {(error) in
failure?(error)
}
}
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, "icon_url": iconURL, "icon_emoji": iconEmoji, "attachments": encodeAttachments(attachments)]
networkInterface.request(.chatPostMessage, token: token, parameters: WebAPI.filterNilParameters(parameters), successClosure: {(response) in
success?((ts: response["ts"] as? String, response["channel"] as? String))
}) {(error) in
failure?(error)
}
}
public func sendMeMessage(_ channel: String, text: String, success: (((ts: String?, channel: String?))->Void)?, failure: FailureClosure?) {
let parameters: [String: Any?] = ["channel": channel, "text": text.slackFormatEscaping]
networkInterface.request(.chatMeMessage, token: token, parameters: WebAPI.filterNilParameters(parameters), successClosure: {(response) in
success?((ts: response["ts"] as? String, response["channel"] as? String))
}) {(error) in
failure?(error)
}
}
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)]
networkInterface.request(.chatUpdate, token: token, parameters: WebAPI.filterNilParameters(parameters), successClosure: {(response) in
success?(true)
}) {(error) in
failure?(error)
}
}
//MARK: - Do Not Disturb
public func dndInfo(_ user: String? = nil, success: ((_ status: DoNotDisturbStatus)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any?] = ["user": user]
networkInterface.request(.dndInfo, token: token, parameters: WebAPI.filterNilParameters(parameters), successClosure: {(response) in
success?(DoNotDisturbStatus(status: response))
}) {(error) in
failure?(error)
}
}
public func dndTeamInfo(_ users: [String]? = nil, success: ((_ statuses: [String: DoNotDisturbStatus])->Void)?, failure: FailureClosure?) {
let parameters: [String: Any?] = ["users": users?.joined(separator: ",")]
networkInterface.request(.dndTeamInfo, token: token, parameters: WebAPI.filterNilParameters(parameters), successClosure: {(response) in
guard let usersDictionary = response["users"] as? [String: Any] else {
success?([:])
return
}
success?(self.enumerateDNDStatuses(usersDictionary))
}) {(error) in
failure?(error)
}
}
//MARK: - Emoji
public func emojiList(_ success: ((_ emojiList: [String: Any]?)->Void)?, failure: FailureClosure?) {
networkInterface.request(.emojiList, token: token, parameters: nil, successClosure: {(response) in
success?(response["emoji"] as? [String: Any])
}) {(error) in
failure?(error)
}
}
//MARK: - Files
public func deleteFile(_ fileID: String, success: ((_ deleted: Bool)->Void)?, failure: FailureClosure?) {
let parameters = ["file": fileID]
networkInterface.request(.filesDelete, token: token, parameters: parameters as [String : Any]?, successClosure: {(response) in
success?(true)
}) {(error) in
failure?(error)
}
}
public func fileInfo(_ fileID: String, commentCount: Int = 100, totalPages: Int = 1, success: ((_ file: File)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any] = ["file": fileID, "count": commentCount, "totalPages": totalPages]
networkInterface.request(.filesInfo, token: token, parameters: parameters, successClosure: {(response) in
var file = File(file: response["file"] as? [String: Any])
(response["comments"] as? [[String: Any]])?.forEach { comment in
let comment = Comment(comment: comment)
if let id = comment.id {
file.comments[id] = comment
}
}
success?(file)
}) {(error) in
failure?(error)
}
}
public func uploadFile(_ file: Data, filename: String, filetype: String = "auto", title: String? = nil, initialComment: String? = nil, channels: [String]? = nil, success: ((_ file: File)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any?] = ["filename": filename, "filetype": filetype, "title": title, "initial_comment": initialComment, "channels": channels?.joined(separator: ",")]
networkInterface.uploadRequest(token, data: file, parameters: WebAPI.filterNilParameters(parameters), successClosure: {(response) in
success?(File(file: response["file"] as? [String: Any]))
}) {(error) in
failure?(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]
networkInterface.request(.filesCommentsAdd, token: token, parameters: parameters, successClosure: {(response) in
success?(Comment(comment: response["comment"] as? [String: Any]))
}) {(error) in
failure?(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]
networkInterface.request(.filesCommentsEdit, token: token, parameters: parameters, successClosure: {(response) in
success?(Comment(comment: response["comment"] as? [String: Any]))
}) {(error) in
failure?(error)
}
}
public func deleteFileComment(_ fileID: String, commentID: String, success: ((_ deleted: Bool?)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any] = ["file": fileID, "id": commentID]
networkInterface.request(.filesCommentsDelete, token: token, parameters: parameters, successClosure: {(response) in
success?(true)
}) {(error) in
failure?(error)
}
}
//MARK: - Groups
public func closeGroup(_ groupID: String, success: ((_ closed: Bool)->Void)?, failure: FailureClosure?) {
close(.groupsClose, channelID: groupID, success: {(closed) in
success?(closed)
}) {(error) in
failure?(error)
}
}
public func groupHistory(_ id: String, latest: String = "\(Date().timeIntervalSince1970)", oldest: String = "0", inclusive: Bool = false, count: Int = 100, unreads: Bool = false, success: ((_ history: History)->Void)?, failure: FailureClosure?) {
history(.groupsHistory, id: id, latest: latest, oldest: oldest, inclusive: inclusive, count: count, unreads: unreads, success: {(history) in
success?(history)
}) {(error) in
failure?(error)
}
}
public func groupInfo(_ id: String, success: ((_ channel: Channel)->Void)?, failure: FailureClosure?) {
info(.groupsInfo, type:.group, id: id, success: {(channel) in
success?(channel)
}) {(error) in
failure?(error)
}
}
public func groupsList(_ excludeArchived: Bool = false, success: ((_ channels: [[String: Any]]?)->Void)?, failure: FailureClosure?) {
list(.groupsList, type:.group, excludeArchived: excludeArchived, success: {(channels) in
success?(channels)
}) {(error) in
failure?(error)
}
}
public func markGroup(_ channel: String, timestamp: String, success: ((_ ts: String)->Void)?, failure: FailureClosure?) {
mark(.groupsMark, channel: channel, timestamp: timestamp, success: {(ts) in
success?(timestamp)
}) {(error) in
failure?(error)
}
}
public func openGroup(_ channel: String, success: ((_ opened: Bool)->Void)?, failure: FailureClosure?) {
let parameters = ["channel":channel]
networkInterface.request(.groupsOpen, token: token, parameters: parameters as [String: Any]?, successClosure: {(response) in
success?(true)
}) {(error) in
failure?(error)
}
}
public func setGroupPurpose(_ channel: String, purpose: String, success: ((_ purposeSet: Bool)->Void)?, failure: FailureClosure?) {
setInfo(.groupsSetPurpose, type: .purpose, channel: channel, text: purpose, success: {(purposeSet) in
success?(purposeSet)
}) {(error) in
failure?(error)
}
}
public func setGroupTopic(_ channel: String, topic: String, success: ((_ topicSet: Bool)->Void)?, failure: FailureClosure?) {
setInfo(.groupsSetTopic, type: .topic, channel: channel, text: topic, success: {(topicSet) in
success?(topicSet)
}) {(error) in
failure?(error)
}
}
//MARK: - IM
public func closeIM(_ channel: String, success: ((_ closed: Bool)->Void)?, failure: FailureClosure?) {
close(.imClose, channelID: channel, success: {(closed) in
success?(closed)
}) {(error) in
failure?(error)
}
}
public func imHistory(_ id: String, latest: String = "\(Date().timeIntervalSince1970)", oldest: String = "0", inclusive: Bool = false, count: Int = 100, unreads: Bool = false, success: ((_ history: History)->Void)?, failure: FailureClosure?) {
history(.imHistory, id: id, latest: latest, oldest: oldest, inclusive: inclusive, count: count, unreads: unreads, success: {(history) in
success?(history)
}) {(error) in
failure?(error)
}
}
public func imsList(_ excludeArchived: Bool = false, success: ((_ channels: [[String: Any]]?)->Void)?, failure: FailureClosure?) {
list(.imList, type:.im, excludeArchived: excludeArchived, success: {(channels) in
success?(channels)
}) {(error) in
failure?(error)
}
}
public func markIM(_ channel: String, timestamp: String, success: ((_ ts: String)->Void)?, failure: FailureClosure?) {
mark(.imMark, channel: channel, timestamp: timestamp, success: {(ts) in
success?(timestamp)
}) {(error) in
failure?(error)
}
}
public func openIM(_ userID: String, success: ((_ imID: String?)->Void)?, failure: FailureClosure?) {
let parameters = ["user": userID]
networkInterface.request(.imOpen, token: token, parameters: parameters as [String: Any]?, successClosure: {(response) in
let group = response["channel"] as? [String: Any]
success?(group?["id"] as? String)
}) {(error) in
failure?(error)
}
}
//MARK: - MPIM
public func closeMPIM(_ channel: String, success: ((_ closed: Bool)->Void)?, failure: FailureClosure?) {
close(.mpimClose, channelID: channel, success: {(closed) in
success?(closed)
}) {(error) in
failure?(error)
}
}
public func mpimHistory(_ id: String, latest: String = "\(Date().timeIntervalSince1970)", oldest: String = "0", inclusive: Bool = false, count: Int = 100, unreads: Bool = false, success: ((_ history: History)->Void)?, failure: FailureClosure?) {
history(.mpimHistory, id: id, latest: latest, oldest: oldest, inclusive: inclusive, count: count, unreads: unreads, success: {(history) in
success?(history)
}) {(error) in
failure?(error)
}
}
public func mpimsList(_ excludeArchived: Bool = false, success: ((_ channels: [[String: Any]]?)->Void)?, failure: FailureClosure?) {
list(.mpimList, type:.group, excludeArchived: excludeArchived, success: {(channels) in
success?(channels)
}) {(error) in
failure?(error)
}
}
public func markMPIM(_ channel: String, timestamp: String, success: ((_ ts: String)->Void)?, failure: FailureClosure?) {
mark(.mpimMark, channel: channel, timestamp: timestamp, success: {(ts) in
success?(timestamp)
}) {(error) in
failure?(error)
}
}
public func openMPIM(_ userIDs: [String], success: ((_ mpimID: String?)->Void)?, failure: FailureClosure?) {
let parameters = ["users": userIDs.joined(separator: ",")]
networkInterface.request(.mpimOpen, token: token, parameters: parameters as [String: Any]?, successClosure: {(response) in
let group = response["group"] as? [String: Any]
success?(group?["id"] as? String)
}) {(error) in
failure?(error)
}
}
//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: {(ok) in
success?(ok)
}) {(error) in
failure?(error)
}
}
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: {(ok) in
success?(ok)
}) {(error) in
failure?(error)
}
}
private func pin(_ endpoint: Endpoint, channel: String, file: String? = nil, fileComment: String? = nil, timestamp: String? = nil, success: ((_ ok: Bool)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any?] = ["channel": channel, "file": file, "file_comment": fileComment, "timestamp": timestamp]
networkInterface.request(endpoint, token: token, parameters: WebAPI.filterNilParameters(parameters), successClosure: {(response) in
success?(true)
}) {(error) in
failure?(error)
}
}
//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: {(ok) in
success?(ok)
}) {(error) in
failure?(error)
}
}
// 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: {(ok) in
success?(ok)
}) {(error) in
failure?(error)
}
}
private func react(_ endpoint: Endpoint, name: String, file: String? = nil, fileComment: String? = nil, channel: String? = nil, timestamp: String? = nil, success: ((_ ok: Bool)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any?] = ["name": name, "file": file, "file_comment": fileComment, "channel": channel, "timestamp": timestamp]
networkInterface.request(endpoint, token: token, parameters: WebAPI.filterNilParameters(parameters), successClosure: {(response) in
success?(true)
}) {(error) in
failure?(error)
}
}
//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: {(ok) in
success?(ok)
}) {(error) in
failure?(error)
}
}
// 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: {(ok) in
success?(ok)
}) {(error) in
failure?(error)
}
}
private func star(_ endpoint: Endpoint, file: String?, fileComment: String?, channel: String?, timestamp: String?, success: ((_ ok: Bool)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any?] = ["file": file, "file_comment": fileComment, "channel": channel, "timestamp": timestamp]
networkInterface.request(endpoint, token: token, parameters: WebAPI.filterNilParameters(parameters), successClosure: {(response) in
success?(true)
}) {(error) in
failure?(error)
}
}
//MARK: - Team
public func teamInfo(_ success: ((_ info: [String: Any]?)->Void)?, failure: FailureClosure?) {
networkInterface.request(.teamInfo, token: token, parameters: nil, successClosure: {(response) in
success?(response["team"] as? [String: Any])
}) {(error) in
failure?(error)
}
}
//MARK: - Users
public func userPresence(_ user: String, success: ((_ presence: String?)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any] = ["user": user]
networkInterface.request(.usersGetPresence, token: token, parameters: parameters, successClosure: {(response) in
success?(response["presence"] as? String)
}) {(error) in
failure?(error)
}
}
public func userInfo(_ id: String, success: ((_ user: User)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any] = ["user": id]
networkInterface.request(.usersInfo, token: token, parameters: parameters, successClosure: {(response) in
success?(User(user: response["user"] as? [String: Any]))
}) {(error) in
failure?(error)
}
}
public func usersList(_ includePresence: Bool = false, success: ((_ userList: [[String: Any]]?)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any] = ["presence": includePresence]
networkInterface.request(.usersList, token: token, parameters: parameters, successClosure: {(response) in
success?(response["members"] as? [[String: Any]])
}) {(error) in
failure?(error)
}
}
public func setUserActive(_ success: ((_ success: Bool)->Void)?, failure: FailureClosure?) {
networkInterface.request(.usersSetActive, token: token, parameters: nil, successClosure: {(response) in
success?(true)
}) {(error) in
failure?(error)
}
}
public func setUserPresence(_ presence: Presence, success: ((_ success: Bool)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any] = ["presence": presence.rawValue]
networkInterface.request(.usersSetPresence, token: token, parameters: parameters, successClosure: {(response) in
success?(true)
}) {(error) in
failure?(error)
}
}
//MARK: - Channel Utilities
private func close(_ endpoint: Endpoint, channelID: String, success: ((_ closed: Bool)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any] = ["channel": channelID]
networkInterface.request(endpoint, token: token, parameters: parameters, successClosure: {(response) in
success?(true)
}) {(error) in
failure?(error)
}
}
private func history(_ endpoint: Endpoint, id: String, latest: String = "\(Date().timeIntervalSince1970)", 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]
networkInterface.request(endpoint, token: token, parameters: parameters, successClosure: {(response) in
success?(History(history: response))
}) {(error) in
failure?(error)
}
}
private func info(_ endpoint: Endpoint, type: ChannelType, id: String, success: ((_ channel: Channel)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any] = ["channel": id]
networkInterface.request(endpoint, token: token, parameters: parameters, successClosure: {(response) in
success?(Channel(channel: response[type.rawValue] as? [String: Any]))
}) {(error) in
failure?(error)
}
}
private func list(_ endpoint: Endpoint, type: ChannelType, excludeArchived: Bool = false, success: ((_ channels: [[String: Any]]?)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any] = ["exclude_archived": excludeArchived]
networkInterface.request(endpoint, token: token, parameters: parameters, successClosure: {(response) in
success?(response[type.rawValue+"s"] as? [[String: Any]])
}) {(error) in
failure?(error)
}
}
private func mark(_ endpoint: Endpoint, channel: String, timestamp: String, success: ((_ ts: String)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any] = ["channel": channel, "ts": timestamp]
networkInterface.request(endpoint, token: token, parameters: parameters, successClosure: {(response) in
success?(timestamp)
}) {(error) in
failure?(error)
}
}
fileprivate func setInfo(_ endpoint: Endpoint, type: InfoType, channel: String, text: String, success: ((_ success: Bool)->Void)?, failure: FailureClosure?) {
let parameters: [String: Any] = ["channel": channel, type.rawValue: text]
networkInterface.request(endpoint, token: token, parameters: parameters, successClosure: {(response) in
success?(true)
}) {(error) in
failure?(error)
}
}
//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 data = try JSONSerialization.data(withJSONObject: attachmentArray, options: [])
return String(data: data, encoding: String.Encoding.utf8)
} catch _ {
}
}
return nil
}
//MARK: - Filter Nil Parameters
internal static func filterNilParameters(_ parameters: [String: Any?]) -> [String: Any] {
var finalParameters = [String: Any]()
for (key, value) in parameters {
if let unwrapped = value {
finalParameters[key] = unwrapped
}
}
return finalParameters
}
//MARK: - Enumerate Do Not Disturb Status
private func enumerateDNDStatuses(_ statuses: [String: Any]) -> [String: DoNotDisturbStatus] {
var retVal = [String: DoNotDisturbStatus]()
for key in statuses.keys {
retVal[key] = DoNotDisturbStatus(status: statuses[key] as? [String: Any])
}
return retVal
}
}
-49
View File
@@ -1,49 +0,0 @@
//
// WebhookRequest.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.
internal struct WebhookRequest: Request {
let token: String?
let teamID: String
let teamDomain: String
let channelID: String
let channelName: String
let userID: String
let userName: String
let command: String
let text: String
let responseURL: String
init(request: [String: Any]?) {
token = request?["token"] as? String
teamID = request?["team_id"] as? String ?? ""
teamDomain = request?["team_domain"] as? String ?? ""
channelID = request?["channel_id"] as? String ?? ""
channelName = request?["channel_name"] as? String ?? ""
userID = request?["user_id"] as? String ?? ""
userName = request?["user_name"] as? String ?? ""
command = request?["command"] as? String ?? ""
text = request?["text"] as? String ?? ""
responseURL = request?["response_url"] as? String ?? ""
}
}
-49
View File
@@ -1,49 +0,0 @@
//
// WebhookServer.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.
open class WebhookServer: Server {
public init(token: String, route: String, response: Response) {
super.init(token: token)
addRoute(route, response: response)
}
open func addRoute(_ route: String, response: Response) {
http["/\(route)"] = { request in
let webhookRequest = WebhookRequest(request: self.dictionaryFromRequest(request.body))
if webhookRequest.token == self.token {
return self.request(webhookRequest, reply: self.replyForResponse(response))
} else {
return .badRequest(.text("Bad request."))
}
}
}
private func replyForResponse(_ response: Response) -> Reply {
if response.attachments == nil && response.responseType == nil {
return Reply.text(body: response.text)
} else {
return Reply.json(response: response)
}
}
}
-28
View File
@@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>3.1.5</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2016 Peter Zignego. All rights reserved.</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>
</plist>
-28
View File
@@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>3.1.5</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2016 Peter Zignego. All rights reserved.</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>
</plist>
+20
View File
@@ -0,0 +1,20 @@
//
// ClientConnection.swift
// SlackKit
//
// Created by Emory Dunn on 12/28/17.
//
import Foundation
public class ClientConnection {
public var client: Client?
public var rtm: SKRTMAPI?
public var webAPI: WebAPI?
public init(client: Client?, rtm: SKRTMAPI?, webAPI: WebAPI?) {
self.client = client
self.rtm = rtm
self.webAPI = webAPI
}
}
+123
View File
@@ -0,0 +1,123 @@
//
// SlackKit.swift
//
// Copyright © 2017 Peter Zignego. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
@_exported import SKClient
@_exported import SKCore
@_exported import SKRTMAPI
@_exported import SKServer
@_exported import SKWebAPI
public final class SlackKit: RTMAdapter {
public typealias EventClosure = (Event, ClientConnection?) -> Void
internal typealias TypedEvent = (EventType, EventClosure)
internal var callbacks = [TypedEvent]()
internal(set) public var server: SKServer?
internal(set) public var clients: [String: ClientConnection] = [:]
/// Return the `SKRTMAPI` instance of the first client
public var rtm: SKRTMAPI? {
return clients.values.first?.rtm
}
/// Return the `WebAPI` instance of the first client
public var webAPI: WebAPI? {
return clients.values.first?.webAPI
}
public init() {}
public func addWebAPIAccessWithToken(_ token: String) {
let webAPI = WebAPI(token: token)
if let clientConnection = clients[token] {
clientConnection.webAPI = webAPI
} else {
clients[token] = ClientConnection(client: nil, rtm: nil, webAPI: webAPI)
}
}
public func addRTMBotWithAPIToken(
_ token: String,
client: Client? = Client(),
options: RTMOptions = RTMOptions(),
rtm: RTMWebSocket? = nil
) {
let rtm = SKRTMAPI(withAPIToken: token, options: options, rtm: rtm)
rtm.adapter = self
if let clientConnection = clients[token] {
clientConnection.rtm = rtm
} else {
clients[token] = ClientConnection(client: client, rtm: rtm, webAPI: nil)
}
clients[token]?.rtm?.connect()
}
public func addServer(_ server: SlackKitServer? = nil, responder: SlackKitResponder? = nil, oauth: OAuthConfig? = nil) {
var responder: SlackKitResponder = responder ?? SlackKitResponder(routes: [])
if let oauth = oauth {
responder.routes.append(oauthRequestRoute(config: oauth))
}
self.server = SKServer(server: server, responder: responder)
self.server?.start()
}
private func oauthRequestRoute(config: OAuthConfig) -> RequestRoute {
let oauth = OAuthMiddleware(config: config) { authorization in
// User
if let token = authorization.accessToken {
self.addWebAPIAccessWithToken(token)
}
// Bot User
if let token = authorization.bot?.botToken {
self.addRTMBotWithAPIToken(token)
}
}
return RequestRoute(path: "/oauth", middleware: oauth)
}
// MARK: - RTM Adapter
public func initialSetup(json: [String: Any], instance: SKRTMAPI) {
clients[instance.token]?.client?.initialSetup(JSON: json)
}
public func notificationForEvent(_ event: Event, type: EventType, instance: SKRTMAPI) {
let clientConnection = clients[instance.token]
clientConnection?.client?.notificationForEvent(event, type: type)
executeCallbackForEvent(event, type: type, clientConnection: clientConnection)
}
public func connectionClosed(with error: Error, instance: SKRTMAPI) {}
// MARK: - Callbacks
public func notificationForEvent(_ type: EventType, event: @escaping EventClosure) {
callbacks.append((type, event))
}
private func executeCallbackForEvent(_ event: Event, type: EventType, clientConnection: ClientConnection?) {
let cbs = callbacks.filter {$0.0 == type}
for callback in cbs {
callback.1(event, clientConnection)
}
}
}
@@ -15,13 +15,11 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>3.1.5</string>
<key>CFBundleSignature</key>
<string>????</string>
<string>4.0.0</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2016 Peter Zignego. All rights reserved.</string>
<string>Copyright © 2017 Peter Zignego. All rights reserved.</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>