Skip to content
Permalink
Browse files

Close #66

  • Loading branch information...
askosh committed Sep 25, 2019
1 parent 0f69ad7 commit c6a3479cb26007567c907885f71e23c04adc7542
@@ -27,8 +27,7 @@
(app-view view)))

(defn- set-up []
(utils/listen-for-viewport-change (fn [screen-width] (rf/dispatch [::events/set-screen-width screen-width])))
(listens/notifications))
(utils/listen-for-viewport-change (fn [screen-width] (rf/dispatch [::events/set-screen-width screen-width]))))

(defn ^:export run []
(rf/dispatch-sync [::events/initialize])
@@ -135,24 +135,10 @@
{})))

(rf/reg-event-fx
::push-notification
(fn [cofx [_ notification]]
(let [reblog? (not (empty? (get notification :reblog)))
name (if reblog? (get-in notification [:reblog :account :display_name]) (get-in notification [:account :display_name]))
handle (if reblog? (get-in notification [:reblog :account :acct]) (get-in notification [:account :acct]))
title (cond (= "follow" (get notification :type)) "You have been followed!"
(= "reblog" (get notification :type)) "Your toot has been boosted!"
(= "favourite" (get notification :type)) "Your toot has been favourited!"
(= "mention" (get notification :type)) "You have been mentioned!"
:else ":)")
content (cond (= "follow" (get notification :type)) (str name " started following you.")
(= "reblog" (get notification :type)) (str name " has boosted your toot.")
(= "favourite" (get notification :type)) (str name " has favourited your toot.")
(= "mention" (get notification :type)) (str name " has mentioned you in a toot.")
:else ":)")]
(js/webkit.messageHandlers.ivorynotification.postMessage (str title "|" content)))
{}))

::set-newest-notification-id-in-store
(fn [cofx [_ id]]
(js/webkit.messageHandlers.ivorySetNewestNotificationId.postMessage (str id))))

(rf/reg-event-fx
::get-notifications
(fn [cofx [_ timeline]]
@@ -163,6 +149,7 @@
:query-params {}
:headers {"Authorization" (str "Bearer " token)}}))]
(when-not (empty? (get response :body))
(rf/dispatch [::set-newest-notification-id-in-store (get (first (get response :body)) :id)])
(rf/dispatch [::set-notifications (get response :body)]))))
{})))

@@ -178,9 +165,9 @@
:query-params {:since_id since-id}
:headers {"Authorization" (str "Bearer " token)}}))]
(when-not (empty? (get response :body))
(rf/dispatch [::push-notification (first (get response :body))])
(rf/dispatch [::set-newest-notification-id-in-store (get (first (get response :body)) :id)])
(rf/dispatch [::set-notifications (concat (get response :body) notifications)]))))
{})))
{})))

(rf/reg-event-fx
::get-older-notifications
@@ -1,12 +1,4 @@
(ns ivory.listens
(:require [re-frame.core :as rf]
[ivory.events :as events]
[ivory.subscriptions :as subscriptions]))

(defn notifications []
(js/setInterval
(fn []
(let [notifications @(rf/subscribe [::subscriptions/notifications])]
(when-not (empty? notifications)
(rf/dispatch [::events/get-newer-notifications]))))
60000))
[ivory.subscriptions :as subscriptions]))
@@ -291,4 +291,90 @@ class App {

}

public func setNewestNotificationIdInStore(id: String) {

guard let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }

let fileUrl = documentDirectoryUrl.appendingPathComponent("newest-notification-id.json")

let write = ["id": id]

do {

let data = try JSONSerialization.data(withJSONObject: write, options: [])
try data.write(to: fileUrl, options: [])

} catch {

print(error)

}

}

public func getNewestNotificationIdInStore(completion: @escaping (_ credentials: String) -> (Void) ) -> Void {

guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }

let fileUrl = documentsDirectoryUrl.appendingPathComponent("newest-notification-id.json")

do {

let data = try Data(contentsOf: fileUrl, options: [])

guard let read = try JSONSerialization.jsonObject(with: data, options: []) as? [String: String] else { return }

completion(read["id"]!)

} catch {

completion("")

}

}

public func getNotificationsSinceId(id: String, completion: @escaping (_ notifications: [[String: Any]]) -> (Void)) -> Void {

self.getCredentialsFromStore() { (credentials) in

self.getTokenFromStore() { (token) in

var request = URLRequest(url: URL(string: "https://" + credentials["instance_url"]! + "/api/v1/notifications?since_id=" + id)!)

request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("Bearer " + token, forHTTPHeaderField: "Authorization")

let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in

if error != nil {

return

}

do {

let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [[String: Any]]

completion(result!)

} catch {

//completion(AnyObject)
}

}

task.resume()

}

}

}

}
@@ -42,7 +42,7 @@ class ContainerController: UIViewController, WKNavigationDelegate, WKScriptMessa
controller.addUserScript(disableCalloutScript)
controller.addUserScript(accessTokenScript)
controller.addUserScript(accessInstanceURLScript)
controller.add(self, name: "ivorynotification")
controller.add(self, name: "ivorySetNewestNotificationId")

let config = WKWebViewConfiguration()
config.userContentController = controller
@@ -66,6 +66,100 @@ class ContainerController: UIViewController, WKNavigationDelegate, WKScriptMessa

self.view.addSubview(fillerView)

/// Notifications
var bgTask = UIBackgroundTaskIdentifier(rawValue: 1)

bgTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
UIApplication.shared.endBackgroundTask(bgTask)
})

let timer = Timer.scheduledTimer(timeInterval: 30.0, target: self, selector: #selector(self.queryNotifications), userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: RunLoop.Mode.default)

}

}

}

@objc func queryNotifications() {

App().getNewestNotificationIdInStore() { (id) in

if id != "" {

App().getNotificationsSinceId(id: id) { (notifications) in

if !notifications.isEmpty {

let notificationId: String = notifications[0]["id"] as! String
let notificationType: String = notifications[0]["type"] as! String
let notificationAccount: [String: Any] = notifications[0]["account"] as! [String: Any]
let notificationAccountAcct: String = notificationAccount["acct"] as! String

App().setNewestNotificationIdInStore(id: notificationId)

let center = UNUserNotificationCenter.current()

center.getNotificationSettings { (settings) in

if settings.authorizationStatus == .authorized {

let content = UNMutableNotificationContent()

if notificationType == "mention" {

content.title = "@" + notificationAccountAcct
content.body = "Mentioned you."

}

if notificationType == "favourite" {

content.title = "@" + notificationAccountAcct
content.body = "Favourited your toot."

}

if notificationType == "reblog" {

content.title = "@" + notificationAccountAcct
content.body = "Boosted your toot."

}

if notificationType == "follow" {

content.title = "@" + notificationAccountAcct
content.body = "Followed you."

}

content.sound = UNNotificationSound.default

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: false)
let identifier = UUID().uuidString
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

center.add(request, withCompletionHandler: { (error) in

if let error = error {

print("Something went wrong")
print(error)

}

})

}

}

}

}

}

}
@@ -89,44 +183,11 @@ class ContainerController: UIViewController, WKNavigationDelegate, WKScriptMessa

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {

if message.name == "ivorynotification" {
if message.name == "ivorySetNewestNotificationId" {

let body = message.body as! String
let center = UNUserNotificationCenter.current()
let id = message.body as! String

center.getNotificationSettings { (settings) in

if settings.authorizationStatus == .authorized {

let content = UNMutableNotificationContent()
content.title = String(body.split(separator: "|")[0])

print(String(body.split(separator: "|")[0]))

content.body = String(body.split(separator: "|")[1])

print(String(body.split(separator: "|")[1]))

content.sound = UNNotificationSound.default

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: false)
let identifier = UUID().uuidString
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

center.add(request, withCompletionHandler: { (error) in

if let error = error {

print("Something went wrong")
print(error)

}

})

}

}
App().setNewestNotificationIdInStore(id: id)

}

0 comments on commit c6a3479

Please sign in to comment.
You can’t perform that action at this time.