2020-04-07 22:25:33 +02:00
|
|
|
//
|
|
|
|
// TwitterFeedProvider.swift
|
|
|
|
// FeedProvider
|
|
|
|
//
|
|
|
|
// Created by Maurice Parker on 4/7/20.
|
|
|
|
// Copyright © 2020 Ranchero Software, LLC. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
2020-04-14 23:47:05 +02:00
|
|
|
import Secrets
|
|
|
|
import OAuthSwift
|
2020-04-15 23:35:09 +02:00
|
|
|
import RSParser
|
|
|
|
|
2020-04-16 03:17:33 +02:00
|
|
|
// TODO: Beef up error handling...
|
|
|
|
public enum TwitterFeedProviderError: Error {
|
2020-04-16 19:07:57 +02:00
|
|
|
case screenNameNotFound
|
2020-04-16 03:17:33 +02:00
|
|
|
case unknown
|
|
|
|
}
|
|
|
|
|
2020-04-15 23:35:09 +02:00
|
|
|
public struct TwitterFeedProvider: FeedProvider {
|
2020-04-07 22:25:33 +02:00
|
|
|
|
2020-04-15 06:19:06 +02:00
|
|
|
private static let server = "api.twitter.com"
|
2020-04-16 03:17:33 +02:00
|
|
|
private static let apiBase = "https://api.twitter.com/1.1/"
|
2020-04-17 11:30:06 +02:00
|
|
|
private static let dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
|
2020-04-15 06:19:06 +02:00
|
|
|
|
2020-04-16 19:07:57 +02:00
|
|
|
private static let userPaths = ["/home", "/notifications"]
|
|
|
|
private static let reservedPaths = ["/search", "/explore", "/messages", "/i", "/compose"]
|
|
|
|
|
2020-04-15 05:33:05 +02:00
|
|
|
public var screenName: String
|
2020-04-15 06:19:06 +02:00
|
|
|
|
|
|
|
private var oauthToken: String
|
|
|
|
private var oauthTokenSecret: String
|
2020-04-15 05:33:05 +02:00
|
|
|
|
2020-04-16 03:17:33 +02:00
|
|
|
private var client: OAuthSwiftClient
|
|
|
|
|
2020-04-15 06:19:06 +02:00
|
|
|
public init?(tokenSuccess: OAuthSwift.TokenSuccess) {
|
2020-04-17 01:19:49 +02:00
|
|
|
guard let screenName = tokenSuccess.parameters["screen_name"] as? String else {
|
2020-04-15 06:19:06 +02:00
|
|
|
return nil
|
|
|
|
}
|
2020-04-15 05:33:05 +02:00
|
|
|
|
2020-04-15 06:19:06 +02:00
|
|
|
self.screenName = screenName
|
|
|
|
self.oauthToken = tokenSuccess.credential.oauthToken
|
|
|
|
self.oauthTokenSecret = tokenSuccess.credential.oauthTokenSecret
|
2020-04-15 05:33:05 +02:00
|
|
|
|
2020-04-17 01:19:49 +02:00
|
|
|
let tokenCredentials = Credentials(type: .oauthAccessToken, username: screenName, secret: oauthToken)
|
2020-04-15 06:19:06 +02:00
|
|
|
try? CredentialsManager.storeCredentials(tokenCredentials, server: Self.server)
|
|
|
|
|
2020-04-17 01:19:49 +02:00
|
|
|
let tokenSecretCredentials = Credentials(type: .oauthAccessTokenSecret, username: screenName, secret: oauthTokenSecret)
|
2020-04-15 06:19:06 +02:00
|
|
|
try? CredentialsManager.storeCredentials(tokenSecretCredentials, server: Self.server)
|
2020-04-16 03:17:33 +02:00
|
|
|
|
|
|
|
client = OAuthSwiftClient(consumerKey: Secrets.twitterConsumerKey,
|
|
|
|
consumerSecret: Secrets.twitterConsumerSecret,
|
|
|
|
oauthToken: oauthToken,
|
|
|
|
oauthTokenSecret: oauthTokenSecret,
|
|
|
|
version: .oauth1)
|
2020-04-15 05:33:05 +02:00
|
|
|
}
|
2020-04-08 17:12:06 +02:00
|
|
|
|
2020-04-17 01:19:49 +02:00
|
|
|
public init?(screenName: String) {
|
2020-04-15 06:03:08 +02:00
|
|
|
self.screenName = screenName
|
2020-04-15 05:33:05 +02:00
|
|
|
|
2020-04-17 01:19:49 +02:00
|
|
|
guard let tokenCredentials = try? CredentialsManager.retrieveCredentials(type: .oauthAccessToken, server: Self.server, username: screenName),
|
|
|
|
let tokenSecretCredentials = try? CredentialsManager.retrieveCredentials(type: .oauthAccessTokenSecret, server: Self.server, username: screenName) else {
|
2020-04-15 06:19:06 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
self.oauthToken = tokenCredentials.secret
|
|
|
|
self.oauthTokenSecret = tokenSecretCredentials.secret
|
2020-04-16 03:17:33 +02:00
|
|
|
|
|
|
|
client = OAuthSwiftClient(consumerKey: Secrets.twitterConsumerKey,
|
|
|
|
consumerSecret: Secrets.twitterConsumerSecret,
|
|
|
|
oauthToken: oauthToken,
|
|
|
|
oauthTokenSecret: oauthTokenSecret,
|
|
|
|
version: .oauth1)
|
2020-04-07 22:25:33 +02:00
|
|
|
}
|
2020-04-15 23:35:09 +02:00
|
|
|
|
|
|
|
public func ability(_ urlComponents: URLComponents, forUsername username: String?) -> FeedProviderAbility {
|
|
|
|
guard urlComponents.host?.hasSuffix("twitter.com") ?? false else {
|
|
|
|
return .none
|
|
|
|
}
|
|
|
|
|
2020-04-16 22:17:22 +02:00
|
|
|
let bestUserName = username != nil ? username : urlComponents.user
|
2020-04-17 01:19:49 +02:00
|
|
|
if bestUserName == screenName {
|
2020-04-15 23:35:09 +02:00
|
|
|
return .owner
|
|
|
|
}
|
|
|
|
|
|
|
|
return .available
|
|
|
|
}
|
|
|
|
|
2020-04-16 18:25:39 +02:00
|
|
|
public func iconURL(_ urlComponents: URLComponents, completion: @escaping (Result<String, Error>) -> Void) {
|
2020-04-16 19:07:57 +02:00
|
|
|
if let screenName = deriveScreenName(urlComponents) {
|
2020-04-17 03:18:47 +02:00
|
|
|
retrieveUser(screenName: screenName) { result in
|
2020-04-17 01:00:27 +02:00
|
|
|
switch result {
|
|
|
|
case .success(let user):
|
|
|
|
if let avatarURL = user.avatarURL {
|
|
|
|
completion(.success(avatarURL))
|
|
|
|
} else {
|
|
|
|
completion(.failure(TwitterFeedProviderError.screenNameNotFound))
|
|
|
|
}
|
|
|
|
case .failure(let error):
|
|
|
|
completion(.failure(error))
|
|
|
|
}
|
|
|
|
}
|
2020-04-16 19:07:57 +02:00
|
|
|
} else {
|
|
|
|
completion(.failure(TwitterFeedProviderError.screenNameNotFound))
|
|
|
|
}
|
2020-04-15 23:35:09 +02:00
|
|
|
}
|
|
|
|
|
2020-04-17 01:00:27 +02:00
|
|
|
public func assignName(_ urlComponents: URLComponents, completion: @escaping (Result<String, Error>) -> Void) {
|
|
|
|
switch urlComponents.path {
|
|
|
|
|
|
|
|
case "/", "/home":
|
|
|
|
let name = NSLocalizedString("Twitter Timeline", comment: "Twitter Timeline")
|
|
|
|
completion(.success(name))
|
|
|
|
|
|
|
|
case "/notifications/mentions":
|
|
|
|
let name = NSLocalizedString("Twitter Mentions", comment: "Twitter Mentions")
|
|
|
|
completion(.success(name))
|
|
|
|
|
|
|
|
case "/search":
|
|
|
|
if let query = urlComponents.queryItems?.first(where: { $0.name == "q" })?.value {
|
|
|
|
let localized = NSLocalizedString("Twitter Search: %@", comment: "Twitter Search")
|
|
|
|
let searchName = NSString.localizedStringWithFormat(localized as NSString, query) as String
|
|
|
|
completion(.success(searchName))
|
|
|
|
} else {
|
|
|
|
let name = NSLocalizedString("Twitter Search", comment: "Twitter Search")
|
|
|
|
completion(.success(name))
|
|
|
|
}
|
|
|
|
|
|
|
|
default:
|
|
|
|
if let screenName = deriveScreenName(urlComponents) {
|
2020-04-17 03:18:47 +02:00
|
|
|
retrieveUser(screenName: screenName) { result in
|
2020-04-17 01:00:27 +02:00
|
|
|
switch result {
|
|
|
|
case .success(let user):
|
|
|
|
if let userName = user.name {
|
2020-04-17 11:30:54 +02:00
|
|
|
completion(.success(userName))
|
2020-04-17 01:00:27 +02:00
|
|
|
} else {
|
|
|
|
completion(.failure(TwitterFeedProviderError.screenNameNotFound))
|
|
|
|
}
|
|
|
|
case .failure(let error):
|
|
|
|
completion(.failure(error))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
completion(.failure(TwitterFeedProviderError.unknown))
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
2020-04-15 23:35:09 +02:00
|
|
|
}
|
2020-04-07 22:25:33 +02:00
|
|
|
|
2020-04-16 18:25:39 +02:00
|
|
|
public func refresh(_ webFeed: WebFeed, completion: @escaping (Result<Set<ParsedItem>, Error>) -> Void) {
|
2020-04-17 11:30:06 +02:00
|
|
|
let api = "statuses/home_timeline.json"
|
2020-04-17 03:18:47 +02:00
|
|
|
|
|
|
|
retrieveTweets(api: api) { result in
|
|
|
|
switch result {
|
|
|
|
case .success(let tweets):
|
2020-04-17 11:30:06 +02:00
|
|
|
let parsedItems = self.makeParsedItems(webFeed.url, tweets)
|
2020-04-17 03:18:47 +02:00
|
|
|
completion(.success(parsedItems))
|
|
|
|
case .failure(let error):
|
|
|
|
completion(.failure(error))
|
|
|
|
}
|
|
|
|
}
|
2020-04-15 23:35:09 +02:00
|
|
|
}
|
|
|
|
|
2020-04-07 22:25:33 +02:00
|
|
|
}
|
2020-04-14 23:47:05 +02:00
|
|
|
|
2020-04-15 23:35:09 +02:00
|
|
|
// MARK: OAuth1SwiftProvider
|
2020-04-15 21:14:33 +02:00
|
|
|
|
|
|
|
extension TwitterFeedProvider: OAuth1SwiftProvider {
|
|
|
|
|
|
|
|
public static var oauth1Swift: OAuth1Swift {
|
|
|
|
return OAuth1Swift(
|
|
|
|
consumerKey: Secrets.twitterConsumerKey,
|
|
|
|
consumerSecret: Secrets.twitterConsumerSecret,
|
|
|
|
requestTokenUrl: "https://api.twitter.com/oauth/request_token",
|
|
|
|
authorizeUrl: "https://api.twitter.com/oauth/authorize",
|
|
|
|
accessTokenUrl: "https://api.twitter.com/oauth/access_token"
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
2020-04-16 03:17:33 +02:00
|
|
|
|
|
|
|
// MARK: Private
|
|
|
|
|
|
|
|
private extension TwitterFeedProvider {
|
|
|
|
|
2020-04-16 19:07:57 +02:00
|
|
|
func deriveScreenName(_ urlComponents: URLComponents) -> String? {
|
2020-04-16 03:17:33 +02:00
|
|
|
let path = urlComponents.path
|
2020-04-16 19:07:57 +02:00
|
|
|
guard !Self.reservedPaths.contains(path) else { return nil }
|
|
|
|
|
|
|
|
if path.isEmpty || Self.userPaths.contains(path) {
|
|
|
|
return screenName
|
2020-04-16 03:17:33 +02:00
|
|
|
} else {
|
|
|
|
return String(path.suffix(from: path.index(path.startIndex, offsetBy: 1)))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-17 03:18:47 +02:00
|
|
|
func retrieveUser(screenName: String, completion: @escaping (Result<TwitterUser, Error>) -> Void) {
|
2020-04-16 03:17:33 +02:00
|
|
|
let url = "\(Self.apiBase)users/show.json"
|
|
|
|
let parameters = ["screen_name": screenName]
|
|
|
|
|
|
|
|
client.get(url, parameters: parameters) { result in
|
|
|
|
switch result {
|
|
|
|
case .success(let response):
|
2020-04-17 01:00:27 +02:00
|
|
|
let decoder = JSONDecoder()
|
|
|
|
do {
|
|
|
|
let user = try decoder.decode(TwitterUser.self, from: response.data)
|
|
|
|
completion(.success(user))
|
|
|
|
} catch {
|
|
|
|
completion(.failure(error))
|
2020-04-16 03:17:33 +02:00
|
|
|
}
|
|
|
|
case .failure(let error):
|
|
|
|
completion(.failure(error))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-17 22:31:13 +02:00
|
|
|
func retrieveTweets(api: String, completion: @escaping (Result<[TwitterStatus], Error>) -> Void) {
|
2020-04-17 03:18:47 +02:00
|
|
|
let url = "\(Self.apiBase)\(api)"
|
2020-04-17 18:20:22 +02:00
|
|
|
let parameters = ["tweet_mode": "extended"]
|
2020-04-17 03:18:47 +02:00
|
|
|
|
|
|
|
client.get(url, parameters: parameters) { result in
|
|
|
|
switch result {
|
|
|
|
case .success(let response):
|
|
|
|
let decoder = JSONDecoder()
|
|
|
|
let dateFormatter = DateFormatter()
|
2020-04-17 11:30:06 +02:00
|
|
|
dateFormatter.dateFormat = Self.dateFormat
|
2020-04-17 03:18:47 +02:00
|
|
|
decoder.dateDecodingStrategy = .formatted(dateFormatter)
|
2020-04-17 18:20:22 +02:00
|
|
|
let jsonString = String(data: response.data, encoding: .utf8)
|
|
|
|
|
|
|
|
let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("twitter.json")
|
|
|
|
print("******** writing to: \(url.path)")
|
|
|
|
try? jsonString?.write(toFile: url.path, atomically: true, encoding: .utf8)
|
|
|
|
|
2020-04-17 03:18:47 +02:00
|
|
|
do {
|
2020-04-17 22:31:13 +02:00
|
|
|
let tweets = try decoder.decode([TwitterStatus].self, from: response.data)
|
2020-04-17 03:18:47 +02:00
|
|
|
completion(.success(tweets))
|
|
|
|
} catch {
|
|
|
|
completion(.failure(error))
|
|
|
|
}
|
|
|
|
case .failure(let error):
|
|
|
|
completion(.failure(error))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-17 22:31:13 +02:00
|
|
|
func makeParsedItems(_ webFeedURL: String, _ statuses: [TwitterStatus]) -> Set<ParsedItem> {
|
2020-04-17 11:30:06 +02:00
|
|
|
var parsedItems = Set<ParsedItem>()
|
|
|
|
|
2020-04-17 22:31:13 +02:00
|
|
|
for status in statuses {
|
|
|
|
guard let idStr = status.idStr, let statusURL = status.url else { continue }
|
2020-04-17 11:30:06 +02:00
|
|
|
|
|
|
|
let parsedItem = ParsedItem(syncServiceID: idStr,
|
|
|
|
uniqueID: idStr,
|
|
|
|
feedURL: webFeedURL,
|
2020-04-17 22:31:13 +02:00
|
|
|
url: statusURL,
|
2020-04-17 11:30:06 +02:00
|
|
|
externalURL: nil,
|
|
|
|
title: nil,
|
|
|
|
language: nil,
|
2020-04-17 22:31:13 +02:00
|
|
|
contentHTML: status.renderAsHTML(),
|
|
|
|
contentText: status.renderAsText(),
|
2020-04-17 17:18:59 +02:00
|
|
|
summary: nil,
|
2020-04-17 11:30:06 +02:00
|
|
|
imageURL: nil,
|
|
|
|
bannerImageURL: nil,
|
2020-04-17 22:31:13 +02:00
|
|
|
datePublished: status.createdAt,
|
2020-04-17 11:30:06 +02:00
|
|
|
dateModified: nil,
|
2020-04-17 22:31:13 +02:00
|
|
|
authors: makeParsedAuthors(status.user),
|
2020-04-17 11:30:06 +02:00
|
|
|
tags: nil,
|
|
|
|
attachments: nil)
|
|
|
|
parsedItems.insert(parsedItem)
|
|
|
|
}
|
|
|
|
|
|
|
|
return parsedItems
|
|
|
|
}
|
|
|
|
|
|
|
|
func makeUserURL(_ screenName: String) -> String {
|
|
|
|
return "https://twitter.com/\(screenName)"
|
|
|
|
}
|
|
|
|
|
2020-04-17 22:31:13 +02:00
|
|
|
func makeParsedAuthors(_ user: TwitterUser?) -> Set<ParsedAuthor>? {
|
|
|
|
guard let user = user else { return nil }
|
|
|
|
return Set([ParsedAuthor(name: user.name, url: user.url, avatarURL: user.avatarURL, emailAddress: nil)])
|
2020-04-17 17:18:59 +02:00
|
|
|
}
|
|
|
|
|
2020-04-16 03:17:33 +02:00
|
|
|
}
|