Skip to content

Commit

Permalink
Merge pull request #9 from MikePT28/feature/translation-api-by-name
Browse files Browse the repository at this point in the history
Feature/translation api by name
  • Loading branch information
MikePT28 committed Nov 30, 2017
2 parents 902ca74 + f94f91c commit 53e53d5
Show file tree
Hide file tree
Showing 4 changed files with 109 additions and 36 deletions.
13 changes: 10 additions & 3 deletions Sources/GeneralContent/SyncQuery.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,16 @@ open class SyncQuery: NSObject {

open fileprivate(set) var locale: Locale = Manager.content.defaultLocale
open fileprivate(set) var moduleName: String?
open fileprivate(set) var moduleId: String = ""
open fileprivate(set) var moduleId: String?
open fileprivate(set) var fromSync: Date?
open fileprivate(set) var toSync: Date?

open var body: [String: Any] {
var dict = [String: Any]()

dict[Keys.ModuleId] = moduleId

if let id = moduleId {
dict[Keys.ModuleId] = id
}

if let name = moduleName {
dict[Keys.ModuleName] = name
Expand Down Expand Up @@ -56,6 +58,11 @@ open class SyncQuery: NSObject {
self.moduleId = moduleId
}

public init(moduleName: String) {
super.init()
self.moduleName = moduleName
}

@discardableResult
open func moduleName(_ name: String?) -> SyncQuery {
self.moduleName = name
Expand Down
34 changes: 27 additions & 7 deletions Sources/Helpers/TranslationsHelper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import Foundation
@objc(HaloTranslationsHelper)
open class TranslationsHelper: NSObject {

fileprivate var moduleId: String = ""
fileprivate var moduleId: String?
fileprivate var moduleName: String?
fileprivate var keyField: String?
fileprivate var valueField: String?
fileprivate var defaultText: String?
Expand All @@ -35,6 +36,15 @@ open class TranslationsHelper: NSObject {
self.valueField = valueField
self.syncQuery = SyncQuery(moduleId: moduleId).locale(locale)
}

public convenience init(moduleName: String, locale: Locale, keyField: String, valueField: String) {
self.init()
self.moduleName = moduleName
self.locale = locale
self.keyField = keyField
self.valueField = valueField
self.syncQuery = SyncQuery(moduleName: moduleName).locale(locale)
}

@objc(addCompletionHandler:)
open func addCompletionHandler(handler: @escaping (Error?) -> Void) -> Void {
Expand Down Expand Up @@ -119,7 +129,11 @@ open class TranslationsHelper: NSObject {

open func clearAllTexts() -> Void {
translationsMap.removeAll()
Manager.content.removeSyncedInstances(moduleId: moduleId)
if let id = moduleId {
Manager.content.removeSyncedInstances(module: id)
} else if let name = moduleId {
Manager.content.removeSyncedInstances(module: name)
}
}

open func load() -> Void {
Expand All @@ -129,14 +143,14 @@ open class TranslationsHelper: NSObject {
}

isLoading = true

Manager.content.sync(query: syncQuery) { moduleId, error in
self.processSyncResult(moduleId: moduleId, error: error)
Manager.content.sync(query: syncQuery) { module, error in
self.processSyncResult(module: module, error: error)
self.completionHandlers.forEach { $0(error) }
}

}

fileprivate func processSyncResult(moduleId: String, error: HaloError?) {
fileprivate func processSyncResult(module : String, error: HaloError?) {

self.isLoading = false

Expand All @@ -145,7 +159,13 @@ open class TranslationsHelper: NSObject {
return
}

let instances = Manager.content.getSyncedInstances(moduleId: moduleId)
var instances : [ContentInstance]
instances = Manager.content.getSyncedInstances(module: module)
setTrasnlationsMap(instances: instances)

}

fileprivate func setTrasnlationsMap(instances : [ContentInstance]){

if let keyField = self.keyField, let valueField = self.valueField {

Expand Down
65 changes: 45 additions & 20 deletions Sources/Managers/ContentManager+Sync.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,30 @@ extension ContentManager {
return ContentManager.filePath.appendingPathComponent(file).path
}

fileprivate func isQueryFromId(_ query: SyncQuery) -> Bool {
if query.moduleId != nil {
return true
} else {
return false
}
}


fileprivate func getModuleIdetifier(query: SyncQuery) -> String{
var filePath = ""
if let moduleId = query.moduleId {
filePath = moduleId
} else if let moduleName = query.moduleName {
filePath = moduleName
}
return filePath;
}

// MARK: Sync instances from a module

public func sync(query: SyncQuery, completionHandler handler: @escaping (String, HaloError?) -> Void) -> Void {

let path = getPath(file: "synctimestamp-\(query.moduleId)")
let path = getPath(file: "synctimestamp-\(getModuleIdetifier(query: query))")

// Check whether we just sync or re-sync all the content (locale changed)
if let sync = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? SyncResult, let from = sync.syncDate {
Expand All @@ -36,7 +55,11 @@ extension ContentManager {
switch any {
case let d as [String: AnyObject]: // Sync response
result = SyncResult(data: d)
result?.moduleId = query.moduleId
if(self.isQueryFromId(query)){
result?.moduleId = self.getModuleIdetifier(query: query)
} else {
result?.moduleName = self.getModuleIdetifier(query: query)
}
result?.locale = query.locale
default: // Everything else
break
Expand All @@ -59,7 +82,7 @@ extension ContentManager {
self.processSyncResult(query, syncResult: syncResult, wasFirstSync: isFirstSync, completionHandler: handler)
case .failure(let e):
Manager.core.logMessage(e.description, level: .error)
handler(query.moduleId, e)
handler(self.getModuleIdetifier(query: query), e)
}
}
}
Expand All @@ -68,20 +91,21 @@ extension ContentManager {
if let result = syncResult {

DispatchQueue.global(qos: .background).async {
var path = self.getPath(file: "synctimestamp-\(result.moduleId)")

var path = self.getPath(file: "synctimestamp-\(self.getModuleIdetifier(query: syncQuery))")

// Get the "old" sync info
if let sync = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? SyncResult, let newLocale = syncResult?.locale {
if sync.locale != newLocale {
self.removeSyncedInstances(moduleId: sync.moduleId)
self.removeSyncedInstances(module: self.getModuleIdetifier(query: syncQuery))
}
}

// Save the new sync info
NSKeyedArchiver.archiveRootObject(result, toFile: path)

// Get the instances (if any)
var instanceIds = NSKeyedUnarchiver.unarchiveObject(withFile: self.getPath(file: "sync-\(result.moduleId)")) as? Set<String> ?? Set<String>()
var instanceIds = NSKeyedUnarchiver.unarchiveObject(withFile: self.getPath(file: "sync-\(self.getModuleIdetifier(query: syncQuery))")) as? Set<String> ?? Set<String>()

result.created.forEach { NSKeyedArchiver.archiveRootObject($0, toFile: self.getPath(file: $0.id!)); instanceIds.insert($0.id!) }
result.updated.forEach { NSKeyedArchiver.archiveRootObject($0, toFile: self.getPath(file: $0.id!)); instanceIds.insert($0.id!) }
Expand All @@ -92,15 +116,15 @@ extension ContentManager {
do {
try FileManager.default.removeItem(atPath: self.getPath(file: instanceId))
} catch {
Manager.core.logMessage("Error deleting instance \(instanceId)", level: .error)
Manager.core.logMessage("Error deleting instance \(self.getModuleIdetifier(query: syncQuery))", level: .error)
}
}

path = self.getPath(file: "sync-\(result.moduleId)")
path = self.getPath(file: "sync-\(self.getModuleIdetifier(query: syncQuery))")
NSKeyedArchiver.archiveRootObject(instanceIds, toFile: path)

// Store a log entry for this sync
path = self.getPath(file: "synclog-\(result.moduleId)")
path = self.getPath(file: "synclog-\(self.getModuleIdetifier(query: syncQuery))")

var logEntries = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? [SyncLogEntry] ?? []
logEntries.append(SyncLogEntry(result: result))
Expand All @@ -113,18 +137,18 @@ extension ContentManager {
self.sync(query: query, completionHandler: handler)
} else {
DispatchQueue.main.async {
handler(result.moduleId, nil)
handler(self.getModuleIdetifier(query: syncQuery), nil)
}
}
}
}
}

@objc(syncedInstancesForModule:)
public func getSyncedInstances(moduleId: String) -> [ContentInstance] {
public func getSyncedInstances(module: String) -> [ContentInstance] {

// Get the ids of the instances for the given module
if let instanceIds = NSKeyedUnarchiver.unarchiveObject(withFile: getPath(file: "sync-\(moduleId)")) as? Set<String> {
if let instanceIds = NSKeyedUnarchiver.unarchiveObject(withFile: getPath(file: "sync-\(module)")) as? Set<String> {
return instanceIds.map { NSKeyedUnarchiver.unarchiveObject(withFile: self.getPath(file: $0)) as! ContentInstance }
} else {
// No instance ids have been found for that module
Expand All @@ -133,30 +157,31 @@ extension ContentManager {
}

@objc(removeSyncedInstancesForModule:)
public func removeSyncedInstances(moduleId: String) -> Void {
let path = getPath(file: "sync-\(moduleId)")
public func removeSyncedInstances(module: String) -> Void {
let path = getPath(file: "sync-\(module)")

if let instanceIds = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? Set<String> {
instanceIds.forEach { instanceId in
try? FileManager.default.removeItem(atPath: self.getPath(file: instanceId))
}
try? FileManager.default.removeItem(atPath: path)
try? FileManager.default.removeItem(atPath: self.getPath(file: "synctimestamp-\(moduleId)"))
clearSyncLog(moduleId: moduleId)
try? FileManager.default.removeItem(atPath: self.getPath(file: "synctimestamp-\(module)"))
clearSyncLog(module: module)
}
}

@objc(syncLogForModule:)
public func getSyncLog(moduleId: String) -> [SyncLogEntry] {
let path = self.getPath(file: "synclog-\(moduleId)")
public func getSyncLog(module: String) -> [SyncLogEntry] {
let path = self.getPath(file: "synclog-\(module)")
return NSKeyedUnarchiver.unarchiveObject(withFile: path) as? [SyncLogEntry] ?? []
}

@objc(clearSyncLogForModule:)
public func clearSyncLog(moduleId: String) -> Void {
let path = self.getPath(file: "synclog-\(moduleId)")
public func clearSyncLog(module: String) -> Void {
let path = self.getPath(file: "synclog-\(module)")

try? FileManager.default.removeItem(atPath: path)
}

}

33 changes: 27 additions & 6 deletions Sources/Managers/CoreManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ open class CoreManager: NSObject, HaloManager, Logger {
public var appCredentials: Credentials?
public var userCredentials: Credentials?

public var env: String?

public var frameworkVersion: String {
return Bundle(identifier: "com.mobgen.Halo")!.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
}
Expand Down Expand Up @@ -114,19 +116,25 @@ open class CoreManager: NSObject, HaloManager, Logger {
let passwordKey = CoreConstants.passwordKey
let environmentKey = CoreConstants.environmentSettingKey

if let clientId = data[clientIdKey] as? String, let clientSecret = data[clientSecretKey] as? String {
self.appCredentials = Credentials(clientId: clientId, clientSecret: clientSecret)
if(self.appCredentials != nil) {
self.setAppCredentials(withClientId: self.appCredentials!.username, withClientSecret: self.appCredentials!.password)
} else if let clientId = data[clientIdKey] as? String, let clientSecret = data[clientSecretKey] as? String {
self.setAppCredentials(withClientId: clientId,withClientSecret: clientSecret)
}

if let username = data[usernameKey] as? String, let password = data[passwordKey] as? String {
self.userCredentials = Credentials(username: username, password: password)
if(self.appCredentials != nil) {
self.setUserCredentials(withUsername: self.appCredentials!.username, withPassword: self.appCredentials!.password)
} else if let username = data[usernameKey] as? String, let password = data[passwordKey] as? String {
self.setUserCredentials(withUsername: username, withPassword: password)
}

if let tags = data[CoreConstants.enableSystemTags] as? Bool {
self.enableSystemTags = tags
}

if let env = data[environmentKey] as? String {
if let envEndpoint = self.env {
self.env = envEndpoint
} else if let env = data[environmentKey] as? String {
self.setEnvironment(env)
}
}
Expand All @@ -143,6 +151,20 @@ open class CoreManager: NSObject, HaloManager, Logger {
super.init()
}

/**
Allows changing the current appcredentials.
*/
public func setAppCredentials(withClientId: String , withClientSecret: String) {
self.appCredentials = Credentials(clientId: withClientId, clientSecret: withClientSecret)
}

/**
Allows changing the current user credential.
*/
public func setUserCredentials(withUsername: String , withPassword: String) {
self.userCredentials = Credentials(username: withUsername, password: withPassword)
}

/**
Allows changing the current environment against which the connections are made. It will imply a setup process again
and that is why a completion handler can be provided. Once the process has finished and the environment is
Expand All @@ -162,7 +184,6 @@ open class CoreManager: NSObject, HaloManager, Logger {
self.setup()
}


fileprivate func setup() {

let handler: (Bool) -> Void = { success in
Expand Down

0 comments on commit 53e53d5

Please sign in to comment.