Skip to content

Commit

Permalink
Merge branch 'feature/REFACTOR' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
ShaneQi committed Jul 23, 2017
2 parents 15f55fe + 1b6001c commit d75dcf9
Show file tree
Hide file tree
Showing 7 changed files with 70 additions and 60 deletions.
11 changes: 1 addition & 10 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,4 @@ services:
- docker

script:
- sudo docker run
-v `pwd`/:/ZEGBot
swift:latest
/bin/sh -c
"
apt-get update;
apt-get install uuid-dev -y;
cd ZEGBot;
swift build;
"
- sudo sh ./scripts/build.sh
12 changes: 12 additions & 0 deletions Package.pins
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"autoPin": true,
"pins": [
{
"package": "SwiftyJSON",
"reason": null,
"repositoryURL": "https://github.com/IBM-Swift/SwiftyJSON.git",
"version": "15.0.6"
}
],
"version": 1
}
3 changes: 1 addition & 2 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import PackageDescription
let package = Package(
name: "ZEGBot",
dependencies: [
.Package(url: "https://github.com/IBM-Swift/SwiftyJSON.git", majorVersion: 15),
.Package(url: "https://github.com/PerfectlySoft/Perfect-CURL.git", versions: Version(0,0,0)..<Version(10,0,0))
.Package(url: "https://github.com/IBM-Swift/SwiftyJSON.git", majorVersion: 15)
]
)
12 changes: 4 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,12 @@ This library wraps the JSON decoding processing, making it easy to decode incomi

This library wraps the processing of converting objects to Telegram Bot API request parameters and the processing of performing request, making it easy to handle incoming update.

**This is a server-side swift library powered by [Perfect](https://github.com/PerfectlySoft/Perfect).
Which will help you build your own Perfect Telegram Bot!**

## Installation

Add this project as a dependency in your Package.swift file.

```swift
.Package(url: "https://github.com/ShaneQi/ZEGBot.git", versions: Version(0,0,0)..<Version(10,0,0))
.Package(url: "https://github.com/shaneqi/ZEGBot.git", majorVersion: 2)
```
## Quick Start

Expand All @@ -28,9 +25,7 @@ import ZEGBot
// Don't forget to fill in your bot token.
let bot = ZEGBot(token: "TYPE YOUR TOKEN HERE")

bot.run(with: {
update, bot in

bot.run { update, bot in
// Handle updates here...

})
Expand Down Expand Up @@ -69,7 +64,7 @@ bot.run(with: {
```swift
...
if let message = update?.message {
bot.send(message: "[Google](https://google.com)", to: message.chat, parseMode: .MARKDOWN, disableWebPagePreview: true, disableNotification: true)
bot.send(message: "[Google](https://google.com)", to: message.chat, parseMode: .markdown, disableWebPagePreview: true, disableNotification: true)
}
...
```
Expand Down Expand Up @@ -134,3 +129,4 @@ Not all the methods are supported, checkout more details on [Telegram Bot API](h

## License
This project is licensed under [Apache License v2.0](http://www.apache.org/licenses/LICENSE-2.0).

35 changes: 23 additions & 12 deletions Sources/Methods.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
// Licensed under Apache License v2.0
//

import PerfectCURL
import cURL
import SwiftyJSON
import Foundation
import Dispatch

/// All methods are performed synchronized.
extension ZEGBot {

@discardableResult
Expand All @@ -23,7 +23,7 @@ extension ZEGBot {

var payload: [String: Any] = [
PARAM.TEXT: text
]
]

if let parseMode = parseMode { payload[PARAM.PARSE_MODE] = parseMode.rawValue }
if disableWebPagePreview { payload[PARAM.DISABLE_WEB_PAGE_PREVIEW] = true }
Expand Down Expand Up @@ -256,19 +256,30 @@ extension ZEGBot {
}

internal func perform(method: String, payload: [String: Any]) -> JSON? {
if let data: Data = performRequest(ofMethod: method, payload: payload) {
return JSON(data: data)
}
return nil
}

guard var bodyBytes = JSON(payload).rawString()?.bytes() else {
private func performRequest(ofMethod method: String, payload: [String: Any]) -> Data? {
guard let bodyData = try? JSON(payload).rawData() else {
Log.warning(onMethod: method)
return nil
}

let curl = CURL()
curl.url = urlPrefix + method
curl.setOption(CURLOPT_POSTFIELDS, v: &bodyBytes)
curl.setOption(CURLOPT_HTTPHEADER, s: PARAM.POST_JSON_HEADER_CONTENT_TYPE)

return JSON(data: Data(bytes: curl.performFully().2))

var resultData: Data?
let semaphore = DispatchSemaphore(value: 0)
var request = URLRequest(url: URL(string: urlPrefix + method)!)
request.httpMethod = "POST"
request.httpBody = bodyData
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let task = URLSession(configuration: .default).dataTask(with: request) { data, _, _ in
resultData = data
semaphore.signal()
}
task.resume()
semaphore.wait()
return resultData
}

}
47 changes: 19 additions & 28 deletions Sources/ZEGBot.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,42 +8,39 @@
// Licensed under Apache License v2.0
//

import cURL
import PerfectCURL
import SwiftyJSON
import Foundation
import Dispatch

public struct ZEGBot {

internal let session = URLSession(configuration: .default)

internal var urlPrefix: String

public init(token: String) {
self.urlPrefix = "https://api.telegram.org/bot"+token+"/"
}

public func run(with handler: @escaping ZEGUpdateHandle ) {

let curl = CURL()
public func run(withHandler handler: @escaping UpdateHandler) {
var offset = 0

let semaphore = DispatchSemaphore(value: 0)
while true {

curl.url = urlPrefix + "getupdates?timeout=60&offset=\(offset)"

guard let updates = ZEGBot.decodeUpdates(from: Data(bytes: curl.performFully().2)) else { continue }

if let lastUpdate = updates.last { offset = lastUpdate.updateId + 1 }

for update in updates {
handler(update, self)
let task = session.dataTask(with: URL(string: urlPrefix + "getupdates?timeout=60&offset=\(offset)")!) { data, _, _ in
guard let updatesData = data,
let updates = ZEGBot.decodeUpdates(from: updatesData) else {
semaphore.signal()
return
}
if let lastUpdate = updates.last { offset = lastUpdate.updateId + 1 }
semaphore.signal()
for update in updates {
handler(update, self)
}
}

task.resume()
semaphore.wait()
}

}

public func run(with handler: ZEGUpdateHandler) {
run(with: handler.handle)
}

}
Expand All @@ -66,10 +63,4 @@ extension ZEGBot {

}

public typealias ZEGUpdateHandle = (Update, ZEGBot) -> Void

public protocol ZEGUpdateHandler {

func handle(update: Update, bot: ZEGBot)

}
public typealias UpdateHandler = (Update, ZEGBot) -> Void
10 changes: 10 additions & 0 deletions scripts/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
sudo docker run \
-v `pwd`/:/ZEGBot \
swift:latest \
/bin/sh -c \
"\
apt-get update;\
apt-get install uuid-dev -y;\
cd ZEGBot;\
swift build;\
"

0 comments on commit d75dcf9

Please sign in to comment.