Sync.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. // Copyright (C) 2016 Inigo Valentin
  2. //
  3. // This file is part of the Gasteizko Margolariak IOS app.
  4. //
  5. // The Gasteizko Margolariak IOS app is free software: you can
  6. // redistribute it and/or modify it under the terms of the
  7. // GNU General Public License as published by the Free Software
  8. // Foundation, either version 3 of the License, or (at your
  9. // option) any later version.
  10. //
  11. // The Gasteizko Margolariak IOS app is distributed in the
  12. // hope that it will be useful, but WITHOUT ANY WARRANTY;
  13. // without even the implied warranty of MERCHANTABILITY or
  14. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
  15. // Public License for more details.
  16. //
  17. // You should have received a copy of the GNU General Public
  18. // License along with the Gasteizko Margolariak IOS app.
  19. // If not, see <http://www.gnu.org/licenses/>.
  20. import Foundation
  21. import CoreData
  22. import UIKit
  23. /**
  24. Class to handle server sync.
  25. */
  26. class Sync{
  27. /**
  28. Starts the sync process.
  29. */
  30. init(){
  31. let url = buildUrl();
  32. sync(url: url)
  33. }
  34. /**
  35. Builds the URL to perform the sync against.
  36. :returns: The URL.
  37. */
  38. func buildUrl() -> URL{
  39. let url = URL(string: "https://margolariak.com/API/v1/sync.php?client=com.margolariak.app")
  40. //TODO add parameters
  41. return url!
  42. }
  43. /**
  44. Performs an asynchronous sync.
  45. It fethes the info from the server and stores as Core Data
  46. :param: url The url to sync.
  47. */
  48. func sync(url: URL){
  49. //Synchronously get data
  50. let task = URLSession.shared.dataTask(with: url) { data, response, error in
  51. guard error == nil else {
  52. print("Sync error")
  53. return
  54. }
  55. guard let data = data else {
  56. print("Data is empty")
  57. return
  58. }
  59. print("Got the Sync JSON")
  60. var strData = String(data:data, encoding: String.Encoding.utf8)
  61. let dataIdx = strData?.indexOf(target: "{\"data\"")
  62. strData = strData!.subStr(start: dataIdx!, end: strData!.length - 1)
  63. //TODO: do something with versions
  64. //Get tables
  65. let dataActivity : [String] = self.getTable(data: strData!, table: "activity")
  66. let dataActivityComment : [String] = self.getTable(data: strData!, table: "activity_comment")
  67. let dataActivityImage : [String] = self.getTable(data: strData!, table: "activity_image")
  68. let dataActivityTag : [String] = self.getTable(data: strData!, table: "activity_tag")
  69. //let dataAlbum : [String] = self.getTable(data: strData!, table: "album")
  70. //let dataFestival : [String] = self.getTable(data: strData!, table: "festival")
  71. //let dataFestivalDay : [String] = self.getTable(data: strData!, table: "festival_day")
  72. //let dataFestivalEvent : [String] = self.getTable(data: strData!, table: "festival_event")
  73. //let dataFestivalEventImage : [String] = self.getTable(data: strData!, table: "festival_event_image")
  74. //let dataFestivalOffer : [String] = self.getTable(data: strData!, table: "festival_offer")
  75. //let dataPeople : [String] = self.getTable(data: strData!, table: "people")
  76. //let dataPhoto : [String] = self.getTable(data: strData!, table: "photo")
  77. //let dataPhotoAlbum : [String] = self.getTable(data: strData!, table: "photo_album")
  78. //let dataPhotoComment : [String] = self.getTable(data: strData!, table: "photo_comment")
  79. //let dataPlace : [String] = self.getTable(data: strData!, table: "place")
  80. //let dataPost : [String] = self.getTable(data: strData!, table: "post")
  81. //let dataPostComment : [String] = self.getTable(data: strData!, table: "post_comment")
  82. //let dataPostImage : [String] = self.getTable(data: strData!, table: "post_image")
  83. //let dataPostTag : [String] = self.getTable(data: strData!, table: "post_tag")
  84. //let dataSponsor : [String] = self.getTable(data: strData!, table: "sponsor")
  85. //One by one, save the received data
  86. self.saveTableActivity(entries : dataActivity)
  87. self.saveTableActivityComment(entries : dataActivityComment)
  88. self.saveTableActivityImage(entries : dataActivityImage)
  89. self.saveTableActivityTag(entries : dataActivityTag)
  90. //TODO: Tester, Debug only
  91. // Test if a entity has entries
  92. let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  93. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  94. context.persistentStoreCoordinator = appDelegate.persistentStoreCoordinator
  95. let fetchRequest: NSFetchRequest<Activity_comment> = Activity_comment.fetchRequest()
  96. do {
  97. //go get the results
  98. let searchResults = try context.fetch(fetchRequest)
  99. print ("Num of results = \(searchResults.count)")
  100. for r in searchResults as [NSManagedObject] {
  101. print("\(r.value(forKey: "id"))")
  102. }
  103. } catch {
  104. print("Error with request: \(error)")
  105. }
  106. //End tester
  107. }
  108. task.resume()
  109. }
  110. func getTable(data: String, table: String) -> [String]{
  111. //Does the table exists?
  112. if data.indexOf(target: table) == nil{
  113. print("No data in table \(table)")
  114. return [String]()
  115. }
  116. let iS : Int? = data.indexOf(target: table)
  117. var str = data.subStr(start: iS!, end: data.length - 1)
  118. let iE : Int? = str.indexOf(target: "}]}")!
  119. str = str.subStr(start: 0, end: iE!)
  120. str = str.subStr(start: table.length + 3,end: str.length - 1)
  121. //Separate the entries
  122. var entries : [String] = str.components(separatedBy: "},{")
  123. //Modify the first and the last one to remove bracers
  124. entries[0] = entries[0].subStr(start: 1, end: entries[0].length - 1)
  125. entries[entries.count - 1] = entries[entries.count - 1].subStr(start: 0, end: entries[entries.count - 1].length - 2)
  126. //Return the array
  127. return entries
  128. }
  129. func saveTableActivity(entries : [String]){
  130. let dateFormatter = DateFormatter()
  131. dateFormatter.timeZone = TimeZone.ReferenceType.local
  132. //Set up context
  133. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  134. let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  135. context.persistentStoreCoordinator = appDelegate.persistentStoreCoordinator
  136. let entity = NSEntityDescription.entity(forEntityName: "Activity", in: context)
  137. var row: NSManagedObject
  138. //Delete all previous entries
  139. let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Activity")
  140. let request = NSBatchDeleteRequest(fetchRequest: fetch)
  141. do {
  142. try context.execute(request)
  143. } catch let error as NSError {
  144. print("Could not clean up Activity entity: \(error), \(error.userInfo)")
  145. } catch {
  146. }
  147. //Loop new entries
  148. for entry in entries{
  149. //Get id
  150. var str = entry
  151. let id : Int = Int(str.subStr(start : str.indexOf(target : "\"id\":")! + 6, end : str.indexOf(target : ",\"")! - 2))!
  152. //Get permalink
  153. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  154. let permalink : String = str.subStr(start : str.indexOf(target : "\"permalink\":")! + 13, end : str.indexOf(target : ",\"")! - 2)
  155. //Get date
  156. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  157. dateFormatter.dateFormat = "yyyy-MM-dd"
  158. let date = dateFormatter.date(from : str.subStr(start : str.indexOf(target : "\"date\":")! + 8, end : str.indexOf(target : ",\"")! - 2))!
  159. //Get city
  160. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  161. let city : String = str.subStr(start : str.indexOf(target : "\"city\":")! + 8, end : str.indexOf(target : ",\"")! - 2)
  162. //Get title_es
  163. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  164. let title_es : String = str.subStr(start : str.indexOf(target : "\"title_es\":")! + 12, end : str.indexOf(target : ",\"")! - 2)
  165. //Get title_en
  166. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  167. let title_en : String = str.subStr(start : str.indexOf(target : "\"title_en\":")! + 12, end : str.indexOf(target : ",\"")! - 2)
  168. //Get title_eu
  169. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  170. let title_eu : String = str.subStr(start : str.indexOf(target : "\"title_eu\":")! + 12, end : str.indexOf(target : ",\"")! - 2)
  171. //Get text_es
  172. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  173. let text_es : String = str.subStr(start : str.indexOf(target : "\"text_es\":")! + 11, end : str.indexOf(target : ",\"")! - 2)
  174. //Get text_eu
  175. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  176. let text_eu : String = str.subStr(start : str.indexOf(target : "\"text_eu\":")! + 11, end : str.indexOf(target : ",\"")! - 2)
  177. //Get text_en
  178. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  179. let text_en : String = str.subStr(start : str.indexOf(target : "\"text_en\":")! + 11, end : str.indexOf(target : ",\"")! - 2)
  180. //Get after_es
  181. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  182. var after_es : String = str.subStr(start : str.indexOf(target : "\"after_es\":")! + 12, end : str.indexOf(target : ",\"")! - 2)
  183. if (after_es == "ul"){ //From "null"
  184. after_es = ""
  185. }
  186. //Get after_en
  187. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  188. var after_en : String = str.subStr(start : str.indexOf(target : "\"after_en\":")! + 12, end : str.indexOf(target : ",\"")! - 2)
  189. if (after_en == "ul"){ //From "null"
  190. after_en = ""
  191. }
  192. //Get after_eu
  193. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  194. var after_eu : String = str.subStr(start : str.indexOf(target : "\"after_eu\":")! + 12, end : str.indexOf(target : ",\"")! - 2)
  195. if (after_eu == "ul"){ //From "null"
  196. after_eu = ""
  197. }
  198. //Get price
  199. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  200. let price : Int = Int(str.subStr(start : str.indexOf(target : "\"price\":")! + 9, end : str.indexOf(target : ",\"")! - 2))!
  201. //Get inscription
  202. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  203. let inscription : Int = Int(str.subStr(start : str.indexOf(target : "\"inscription\":")! + 15, end : str.indexOf(target : ",\"")! - 2))!
  204. //Get max_people
  205. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  206. let maxPeoplePre : String = str.subStr(start : str.indexOf(target : "\"max_people\":")! + 14, end : str.indexOf(target : ",")! - 2)
  207. var maxPeople = -1
  208. if (maxPeoplePre != "ul"){ //From "null"
  209. maxPeople = Int(maxPeoplePre)!
  210. }
  211. //Get album
  212. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  213. let albumPre = str.subStr(start : str.indexOf(target : "\"album\":")! + 9, end : str.length - 2)
  214. var album = -1
  215. if (albumPre != "ul"){ //From "null"
  216. album = Int(albumPre)!
  217. }
  218. //Skipping dtime
  219. //Skipping comments
  220. //Save CoreData
  221. row = NSManagedObject(entity: entity!, insertInto: context)
  222. //set the entity values
  223. row.setValue(id, forKey: "id")
  224. row.setValue(permalink, forKey: "permalink")
  225. row.setValue(date, forKey: "date")
  226. row.setValue(city, forKey: "city")
  227. row.setValue(title_es, forKey: "title_es")
  228. row.setValue(title_en, forKey: "title_en")
  229. row.setValue(title_eu, forKey: "title_eu")
  230. row.setValue(text_es, forKey: "text_es")
  231. row.setValue(text_en, forKey: "text_en")
  232. row.setValue(text_eu, forKey: "text_eu")
  233. row.setValue(after_es, forKey: "after_es")
  234. row.setValue(after_en, forKey: "after_en")
  235. row.setValue(after_eu, forKey: "after_eu")
  236. row.setValue(price, forKey: "price")
  237. row.setValue(inscription, forKey: "inscription")
  238. row.setValue(maxPeople, forKey: "max_people")
  239. if (album != -1){
  240. row.setValue(album, forKey: "album")
  241. }
  242. do {
  243. try context.save()
  244. } catch let error as NSError {
  245. print("Could not store Activity with id \(id) \(error), \(error.userInfo)")
  246. } catch {
  247. }
  248. }
  249. }
  250. func saveTableActivityComment(entries : [String]){
  251. let dateFormatter = DateFormatter()
  252. dateFormatter.timeZone = TimeZone.ReferenceType.local
  253. //Set up context
  254. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  255. let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  256. context.persistentStoreCoordinator = appDelegate.persistentStoreCoordinator
  257. let entity = NSEntityDescription.entity(forEntityName: "Activity_comment", in: context)
  258. var row: NSManagedObject
  259. //Delete all previous entries
  260. let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Activity_comment")
  261. let request = NSBatchDeleteRequest(fetchRequest: fetch)
  262. do {
  263. try context.execute(request)
  264. } catch let error as NSError {
  265. print("Could not clean up Activity_comment entity: \(error), \(error.userInfo)")
  266. } catch {
  267. }
  268. //Loop new entries
  269. for entry in entries{
  270. //Get id
  271. var str = entry
  272. let id : Int = Int(str.subStr(start : str.indexOf(target : "\"id\":")! + 6, end : str.indexOf(target : ",\"")! - 2))!
  273. //Get activity
  274. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  275. let activity : String = str.subStr(start : str.indexOf(target : "\"activity\":")! + 12, end : str.indexOf(target : ",\"")! - 2)
  276. //Get text
  277. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  278. let text : String = str.subStr(start : str.indexOf(target : "\"text\":")! + 8, end : str.indexOf(target : ",\"")! - 2)
  279. //Get dtime
  280. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  281. dateFormatter.dateFormat = "yyyy-MM-dd"
  282. let dtime = dateFormatter.date(from : str.subStr(start : str.indexOf(target : "\"dtime\":")! + 9, end : str.indexOf(target : ",\"")! - 2))!
  283. //Get username
  284. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  285. let username : String = str.subStr(start : str.indexOf(target : "\"username\":")! + 12, end : str.indexOf(target : ",\"")! - 2)
  286. //Get lang
  287. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  288. let lang : String = str.subStr(start : str.indexOf(target : "\"lang\":")! + 8, end : str.length - 1)
  289. //Save CoreData
  290. row = NSManagedObject(entity: entity!, insertInto: context)
  291. row.setValue(id, forKey: "id")
  292. row.setValue(activity, forKey: "activity")
  293. row.setValue(text, forKey: "text")
  294. row.setValue(dtime, forKey: "dtime")
  295. row.setValue(username, forKey: "username")
  296. row.setValue(lang, forKey: "lang")
  297. do {
  298. try context.save()
  299. } catch let error as NSError {
  300. print("Could not store Activity_comment with id \(id) \(error), \(error.userInfo)")
  301. } catch {
  302. }
  303. }
  304. }
  305. func saveTableActivityImage(entries : [String]){
  306. //Set up context
  307. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  308. let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  309. context.persistentStoreCoordinator = appDelegate.persistentStoreCoordinator
  310. let entity = NSEntityDescription.entity(forEntityName: "Activity_image", in: context)
  311. var row: NSManagedObject
  312. //Delete all previous entries
  313. let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Activity_image")
  314. let request = NSBatchDeleteRequest(fetchRequest: fetch)
  315. do {
  316. try context.execute(request)
  317. } catch let error as NSError {
  318. print("Could not clean up Activity_comment entity: \(error), \(error.userInfo)")
  319. } catch {
  320. }
  321. //Loop new entries
  322. for entry in entries{
  323. //Get id
  324. var str = entry
  325. let id : Int = Int(str.subStr(start : str.indexOf(target : "\"id\":")! + 6, end : str.indexOf(target : ",\"")! - 2))!
  326. //Get activity
  327. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  328. let activity : Int = Int(str.subStr(start : str.indexOf(target : "\"activity\":")! + 12, end : str.indexOf(target : ",\"")! - 2))!
  329. //Get image
  330. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  331. let image : String = str.subStr(start : str.indexOf(target : "\"image\":")! + 9, end : str.indexOf(target : ",\"")! - 2)
  332. //Get idx
  333. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  334. let idx : Int = Int(str.subStr(start : str.indexOf(target : "\"idx\":")! + 7, end : str.length - 2))!
  335. //Save CoreData
  336. row = NSManagedObject(entity: entity!, insertInto: context)
  337. row.setValue(id, forKey: "id")
  338. row.setValue(activity, forKey: "activity")
  339. row.setValue(image, forKey: "image")
  340. row.setValue(idx, forKey: "idx")
  341. do {
  342. try context.save()
  343. } catch let error as NSError {
  344. print("Could not store Activity_image with id \(id) \(error), \(error.userInfo)")
  345. } catch {
  346. }
  347. }
  348. }
  349. func saveTableActivityTag(entries : [String]){
  350. //Set up context
  351. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  352. let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  353. context.persistentStoreCoordinator = appDelegate.persistentStoreCoordinator
  354. let entity = NSEntityDescription.entity(forEntityName: "Activity_tag", in: context)
  355. var row: NSManagedObject
  356. //Delete all previous entries
  357. let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Activity_tag")
  358. let request = NSBatchDeleteRequest(fetchRequest: fetch)
  359. do {
  360. try context.execute(request)
  361. } catch let error as NSError {
  362. print("Could not clean up Activity_tag entity: \(error), \(error.userInfo)")
  363. } catch {
  364. }
  365. //Loop new entries
  366. for entry in entries{
  367. //Get activity
  368. var str = entry
  369. let activity : Int = Int(str.subStr(start : str.indexOf(target : "\"activity\":")! + 12, end : str.indexOf(target : ",\"")! - 2))!
  370. //Get tag
  371. str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
  372. let tag : String = str.subStr(start : str.indexOf(target : "\"tag\":")! + 7, end : str.length - 1)
  373. //Save CoreData
  374. row = NSManagedObject(entity: entity!, insertInto: context)
  375. row.setValue(activity, forKey: "activity")
  376. row.setValue(tag, forKey: "tag")
  377. do {
  378. try context.save()
  379. } catch let error as NSError {
  380. print("Could not store Activity_tag for activity: \(activity), tag: \(tag). Error: \(error), \(error.userInfo)")
  381. } catch {
  382. }
  383. }
  384. }
  385. }