-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBIHappyAPI.swift
executable file
·897 lines (703 loc) · 30.4 KB
/
BIHappyAPI.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
//
// BIHappyAPI.swift
// BIHappy.eu
//
// Created by Wesley de Groot on 12-10-16.
// Copyright © 2016 WDGWV. All rights reserved.
//
// Just So Swifty!
import Foundation
// Import WebKit for use of WKWebView and UIWebView
import WebKit
// Import UIKit for all the UI* functions
import UIKit
/**
**BIHappy Europe™** *API*
The official BIHappy Europe™ API
**Version:** 0.0.1
**Status:** Beta
**Website:** https://www.bihappy.eu/#api
**Supported permissions:** user, manageAccount/profile, notifications
**Supported functions:** Login, Userlist, Profile images
let BIHappy = BIHappyAPI.sharedInstance
BIHappy.registerKEY("myAPIkeyGoesHere");
// In the API settings you can change Sandbox Mode
// Ask via BIHappy.eu (default)
BIHappy.login(permissions: ["profile"]) { result in
if (result) {
print("Welcome \(BIHappy.user)")
} else {
print("Failed")
}
}
// Native example (if default doesn't fit)
// (even the official app is using above example)
if (BIHappy.login(username: "Username",
password: "Password)) {
let tok = BIHappy.grabToken(); // valid: 24h
}
**Please allow a connection to:** *https://www.bihappy.eu/api/001/\**
*/
open class BIHappyAPI: NSObject, UIWebViewDelegate, WKNavigationDelegate {
/**
This is the shared instance of the BIHappy API
*/
static let sharedInstance = BIHappyAPI()
/**
Disable direct calling of the class
private override.
*/
fileprivate override init() {
self.apiURL = "\(self.apiURL)/\(self.apiVer)"
}
/**
The API Version
For registering your API Version.
*/
fileprivate let apiVer: String = "001"
/**
The API KEY
set your key via `BIHappyAPI().registerKEY(YOURKEYHERE);`
defaults to: 098f6bcd4621d373cade4e832627b4f6
*Please note:* Temporary key will be banned for **24h** after **5** calls.
*/
fileprivate var apiKEY: String = UserDefaults.standard.value(forKey: "BIHappyAPIKey") as! String? ?? "098f6bcd4621d373cade4e832627b4f6"
/**
The API URL
defaults to: https://www.bihappy.eu/api/
*/
fileprivate var apiURL: String = "https://www.bihappy.eu/api"
//TODO: Remove this...
/**
The Action library (**Deprecated**)
Translating actions to the correct URL for this api version
*/
fileprivate let actions: [String: String] = [
"login": "/user/login", // + /withPermissions/requestedPermissions
"logout": "/user/logout",
"session": "/user/session", // Get session token
"profile": "/user/profile", // Get current profile
"notifications": "/user/notifications",
"readnotification": "/user/notification/%s/read",
"viewprofile": "/user/profile/of/%s",
"finduser": "/user/find",
"changePassword": "/user/changepassword" // Post, only selected platforms
]
/**
BIHappy API (POST) Do we got the data?
*/
fileprivate var BIHAPIPOSTGotData: Bool = false
/**
BIHappy API (POST) Which data?
*/
fileprivate var BIHAPIPOSTData: [String: String] = [:]
/**
BIHappy API (GET) Do we got the data?
*/
fileprivate var BIHAPIGETGotData: Bool = false
/**
BIHappy API (GET) Which data?
*/
fileprivate var BIHAPIGETData: [String: String] = [:]
/**
BIHappy API waiting for login?
*/
fileprivate var BIHAPILogin: Bool = false
/**
BIHappy API is the login successfull?
*/
fileprivate var BIHAPIisLoggedin: Bool = false
/**
BIHappy API token
*/
fileprivate var BIHappyToken: String = UserDefaults.standard.value(forKey: "BIHappyAPIToken") as! String? ?? "INVALID_TOKEN_FOR_USER"
/**
BIHappy API use WKWebView? (default: true)
*/
fileprivate let useWKWebView: Bool = true
/**
Had registered a key?
*/
fileprivate var BIHappyKeyRegistered: Bool = false
/**
BIHappy API which user is logged in?
*/
open var user: String = UserDefaults.standard.value(forKey: "BIHappyAPIUser") as! String? ?? "None"
/**
BIHappy API's NSCache for images
*/
fileprivate let BIHappyImageCache = NSCache<NSString, UIImage>()
/**
BIHappy API's Temporary Directory
*/
fileprivate let BIHappyTemporaryDirectory = NSTemporaryDirectory()
/**
BIHappy API's Integrated insecure characters (for URLs)
*/
fileprivate let BIHappyInsecureCharacters = [";", "/", "?", ":", "@", "=", "&", "\"", "<", ">", "#", "%", "{", "}", "|", "\\", "^", "~", "[", "]", "`", "$", "!", "*", "'", "(", ")", ","]
/**
Translates JSON to a Dictionary
- parameter text: the plain text JSON String
- returns: JSON translated to Dictionary
*/
fileprivate func convertStringToDictionary(_ text: String) -> [String: AnyObject]? {
if let data = text.data(using: String.Encoding.utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}
/**
Load a url as GET
- parameter url: the URL
- returns: page contents
*/
@discardableResult open func BIHappyLoad(_ url: String) -> String {
return self.BIApiGetAsText(url)
}
fileprivate func BIHAPIGet(_ action: String) -> [String: String] {
// ?
return ["GET": "GET"]
}
/**
BIHappy API (POST)
- parameter action: which action do we use
- parameter post: data we'll need to send
- returns: Array of data
*/
fileprivate func BIHAPIPost(_ action: String, post: [String: String]) -> [String: String] {
// if no key is registered, register last, or default api key!
if (!BIHappyKeyRegistered) {
// register key (last, or default api key)
self.registerKEY(self.apiKEY)
}
// print("URL=\(apiURL)\(apiKEY)\(actions[action]!)")
// Create empty post string
var postString:String = "";
// Add values
for (name, value) in post {
postString = postString.appending("\(name)=\(value)&")
}
// Add dummy value
postString = postString.appending("via=BIHappyAPIinterface")
// Create the request
var request = URLRequest(url: URL(string: "\(apiURL)\(apiKEY)\(actions[action]!)")!)
// Set HTTP Method to POST
request.httpMethod = "POST"
// encode for posting...
request.httpBody = postString.data(using: .utf8)
// do post it
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // if we got no data
// general error
self.BIHAPIPOSTData = ["Status": "Error: \(String(describing: error))"]
// tell the loop that we got some data
self.BIHAPIPOSTGotData = true
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
// WE DIDN'T GET A: HTTP/1.0 200 found
self.BIHAPIPOSTData = ["Status": "Error \(httpStatus.statusCode)"]
// tell the loop that we got some data
self.BIHAPIPOSTGotData = true
return
}
// there is a response
let responseString = String(data: data, encoding: .utf8)
// convert to [string: string]
self.BIHAPIPOSTData = self.convertStringToDictionary(responseString!)! as! [String : String]
// tell the loop that we got some data
self.BIHAPIPOSTGotData = true
}
// (run) the task!
task.resume()
// waiting for data...
while (!self.BIHAPIPOSTGotData) {
// waiting
}
// return data
return self.BIHAPIPOSTData
}
/**
Make a screenshot from the current active window
- returns: UIImage
*/
fileprivate func screenShotMethod() -> UIImage {
// get the key window's layer!
let layer = UIApplication.shared.keyWindow!.layer
// get the scale
let scale = UIScreen.main.scale
// create a imagecontext
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
// render the layer!
layer.render(in: UIGraphicsGetCurrentContext()!)
// render a screenshot
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
// we're done with UIGraphics
UIGraphicsEndImageContext()
// Return our loved screenshot
return screenshot!
}
/**
BIHappy Login
- parameter permissions: ...
- returns: bool true/false
*/
open func login(_ permissions: [String], completionHandler: @escaping (Bool) -> ()) {
// if no key is registered, register last, or default api key!
if (!BIHappyKeyRegistered) {
// register key (last, or default api key)
self.registerKEY(self.apiKEY)
}
// Local development server.
if (needToLogin()) {
// translate our permissions
let permissions = permissions.joined(separator: ",")
// Create LOCAL a URLRequest for handling the API
//let req = URLRequest(url: NSURL(string: "http://127.0.0.1:8000/?withPermissions=\(permissions.joined(separator: ","))") as! URL)
// Create a URLRequest for handling the API
let req = URLRequest(url: URL(string: "\(apiURL)/user/login/withPermissions/\(permissions)")! as URL)
// Init a empty view controller for use of the blur and webview.
let vc = UIViewController.init(nibName: nil, bundle: nil)
// we want a screenshot as background
vc.view.backgroundColor = UIColor(patternImage: screenShotMethod())
// init UIBlurEffect
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.extraLight)
// set the blur
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = vc.view.bounds
blurEffectView.alpha = 0.5
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// and we append a blur effect to the background
vc.view.addSubview(blurEffectView)
// What do we want for our webview.
// The border's height
let borderHeight: CGFloat = 100
// The border's spacing (from the side of the screen)
let borderSide: CGFloat = 40
// create a super x (x-position on screen)
let x: CGFloat = vc.view.bounds.origin.x + borderSide
// create a super y (y-position on screen)
let y: CGFloat = vc.view.bounds.origin.y + borderHeight
// create our width
let width: CGFloat = vc.view.bounds.size.width - (borderSide * 2)
// create our height
let height: CGFloat = vc.view.bounds.size.height - (borderHeight * 2)
// Do we use a WKWebView (defaults to true)
if (self.useWKWebView) {
// Init the WKWebView
let wk = WKWebView.init(frame: CGRect(x: x, y: y, width: width, height: height))
// Load a HTMLString (when the users see 'loading'
wk.loadHTMLString("<center><h1>Loading...</h1></center>", baseURL: nil)
// Load the request for the API
wk.load(req)
// The screen isn't opaque
wk.isOpaque = false
// The background is clear (transparent)
wk.backgroundColor = UIColor.clear
// the delegate is BIHappyAPI
wk.navigationDelegate = self
// Disable the scrolling
wk.scrollView.isScrollEnabled = false
// Add the WKWebView to our 'new' UIViewController
vc.view.addSubview(wk)
} else {
// Init the UIWebView
let wv = UIWebView.init(frame: CGRect(x: x, y: y, width: width, height: height))
// Load a HTMLString (when the users see 'loading'
wv.loadHTMLString("<center><h1>Loading...</h1></center>", baseURL: nil)
// Load the request for the API
wv.loadRequest(req)
// The screen isn't opaque
wv.isOpaque = false
// The background is clear (transparent)
wv.backgroundColor = UIColor.clear
// the delegate is BIHappyAPI
wv.delegate = self
// Disable the scrolling
wv.scrollView.isScrollEnabled = false
// Add the UIWebView to our 'new' UIViewController
vc.view.addSubview(wv)
}
// Present our 'new' UIViewController
UIApplication.shared.keyWindow?.rootViewController?.present(vc, animated: true, completion: nil)
} else {
// Grab info, if needed
self.BIHappyToken = UserDefaults.standard.value(forKey: "BIHappyAPIToken") as! String? ?? "INVALID_TOKEN_FOR_USER"
// Tell the API we're logged in
self.BIHAPIisLoggedin = true
// Tell the waiter we're logged in
self.BIHAPILogin = true
}
DispatchQueue.global().async {
while !self.BIHAPILogin {
// wait
}
DispatchQueue.main.async {
let formatter = DateFormatter()
formatter.locale = NSLocale.current
formatter.dateFormat = "yyyymmddHHmmss"
let date = Calendar.current.date(byAdding: .month, value: 3, to: Date())
let calculator = Int(formatter.string(from: date!))! // 7890000 = 3 months (fails on newyear).
UserDefaults.standard.set(self.BIHappyToken, forKey: "BIHappyAPIToken")
UserDefaults.standard.set("\(calculator)", forKey: "BIHappyAPIValid")
UserDefaults.standard.set("\(self.user)", forKey: "BIHappyAPIUser")
UIApplication.shared.keyWindow?.rootViewController?.dismiss(animated: true, completion: nil)
completionHandler(self.BIHAPIisLoggedin)
}
}
}
/**
BIHappy Login
- parameter username: username
- parameter password: password
- returns: bool true/false
*/
open func login(_ username: String, password: String) -> Bool {
// if no key is registered, register last, or default api key!
if (!BIHappyKeyRegistered) {
// register key (last, or default api key)
self.registerKEY(self.apiKEY)
}
let token = BIHAPIPost("login", post: [
"username": username,
"password": password
])
self.BIHappyToken = token["status"]!
if (self.isValidToken(token["status"]!)) {
// token is valid
return true
} else {
return false
}
}
/**
Is this token valid:
a valid token does not starts with:
- ERROR
- NONE
- DENIED
- parameter token: token
- returns: bool true/false
*/
fileprivate func isValidToken(_ token: String) -> Bool {
return (token != "ERROR" && token != "NONE" && token != "DENIED")
}
/**
BIHappy grabToken
- returns: token whenever it is valid or invalid!
*/
open func grabToken() -> String {
// if no key is registered, register last, or default api key!
if (!BIHappyKeyRegistered) {
// register key (last, or default api key)
self.registerKEY(self.apiKEY)
}
if (self.BIHAPILogin) {
// ok
if (!self.isValidToken(self.BIHappyToken)) {
// Loading token...
// Please wait...
print("Something went wrong!")
return "ERROR"
} else {
return self.BIHappyToken
}
} else {
return self.BIHappyToken
}
}
/**
get the profile image of a user in your image view.
no need for threads, this function will take care of it.
- parameter forID: user id
- parameter at: at which imageview?
*/
open func getProfileImage(_ forID: Int, at: UIImageView) {
// if no key is registered, register last, or default api key!
if (!BIHappyKeyRegistered) {
// register key (last, or default api key)
self.registerKEY(self.apiKEY)
}
// define our image URL
let imageURL = "https://www.bihappy.eu/images/profile_images/\(forID).png"
// Load image from imageCache
if let cacheImage = BIHappyImageCache.object(forKey: imageURL as NSString!) as UIImage? {
// To be sure, run on the mainthread if the command is runned outside a main tread
DispatchQueue.main.async {
// set the image
at.image = cacheImage
}
return
}
// Download image? or get it from the cache (async), and save it.
DispatchQueue.global(qos: .background).async {
do {
// create the image url
let fileStore = "\(self.BIHappyTemporaryDirectory)\(forID).png"
// Does it exists?
if (FileManager().fileExists(atPath: fileStore)) {
// get the file attibutes
let fm = try FileManager().attributesOfItem(atPath: fileStore)
// get the filetime
let fileTime = fm[FileAttributeKey.creationDate] as? Date
// add 0 to timeinterval!
let ourTime = Date().addingTimeInterval(0)
// is it valid?
if (round((fileTime?.timeIntervalSince(ourTime))!) < 86400) {
// Can we unwrap it?
if let image = UIImage(contentsOfFile: fileStore) {
// Send it to the main queue
DispatchQueue.main.async {
// set the image
at.image = image
// save to memory
self.BIHappyImageCache.setObject(image, forKey: (imageURL as NSString!))
// useless return
return
}
// we did return, so stop loading this function
return
}
}
// else { } // IMAGE NEED A REFRESH, DON'T RETURN
}
// can we download?
let _imageData = try Data.init(contentsOf: URL(string: imageURL)!)
// can we write, with the "?" we suppress errors, errors will not help us saving
try? _imageData.write(to: URL(fileURLWithPath: fileStore), options: .atomic)
// display the image
let imageContents = UIImage.init(data: _imageData)
// the mainqueue
DispatchQueue.main.async {
// if the image is not nil
if (imageContents != nil) {
//save to memory
self.BIHappyImageCache.setObject(imageContents!, forKey: (imageURL as NSString!))
// and set image
at.image = imageContents
}
}
}
catch { }
}
}
/**
filter those nasty characters from url's
- parameter url: the url with possible weird characters
- returns: a clean string
*/
fileprivate func URLtoSafeName(_ url: String) -> String {
// make the URL changeable
var _changeable = url
// loop trough the insecure characters
for change in self.BIHappyInsecureCharacters {
// replace them
_changeable = change.replacingOccurrences(of: change, with: "-")
}
// return our safe string
return _changeable
}
/**
register BIHappy API key for use.
*want to test first*? **temporary key**:
`098f6bcd4621d373cade4e832627b4f6`
*Please note:* Temporary key will be banned for **24h** after **5** calls (per-IP).
- parameter key: your personal BIHappy API key
*/
open func registerKEY(_ key: String) -> Void {
if (key != "") {
if (key == "098f6bcd4621d373cade4e832627b4f6") {
print("[BIHappy API] WARNING: USING A DEVELOPER KEY, PLEASE REGISTER YOUR OWN KEY AT:")
print("[BIHappy API] https://www.bibappy.eu/#api")
}
self.apiKEY = key
self.apiURL = self.apiURL.appending("/\(self.apiKEY)")
self.BIHappyKeyRegistered = true
UserDefaults.standard.set(key, forKey: "BIHappyAPIKey")
} else {
self.registerKEY("098f6bcd4621d373cade4e832627b4f6")
}
}
/**
**BIHappy Forum**
All parameters are optional!
- parameter sub: the subforum where you want to fetch the topics of
- parameter topic: the topic where you want fetch the contents of
- returns: a `Array<Any>` with the contents
*/
open func loadForum(_ sub: String? = nil, topic: String? = nil) -> Array<Any> {
if (!BIHappyKeyRegistered) {
// register key (last, or default api key)
self.registerKEY(self.apiKEY)
}
if (sub == nil && topic == nil) {
print("Load forum Subs")
let json = BIApiGetAsText("\(self.apiURL)/forum/main")
// print(json)
let data = convertStringToDictionary(json)
// print(data)
return (data?["data"])! as! Array<Any>
} else if (sub != nil && topic == nil) {
print("Load Subs")
let json = BIApiGetAsText("\(self.apiURL)/forum/sub/id/\(String(describing: sub))")
// print(json)
let data = convertStringToDictionary(json)
// print(data)
return (data?["data"])! as! Array<Any>
} else if (sub != nil && topic != nil) {
print("Load topic + reactions")
let json = BIApiGetAsText("\(self.apiURL)/forum/topic/id/\(String(describing: topic))")
// print(json)
let data = convertStringToDictionary(json)
// print(data)
return (data?["data"])! as! Array<Any>
} else {
print("⚠ Invalid call")
}
return Array<Any>()
}
open func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
print("[WV] Wekit error: \(error.localizedDescription)")
self.BIHappyToken = "ERROR"
self.BIHAPIisLoggedin = false
self.BIHAPILogin = true
}
open func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("[WK] Wekit error: \(error.localizedDescription)")
self.BIHappyToken = "ERROR"
self.BIHAPIisLoggedin = false
self.BIHAPILogin = true
}
open func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("document.body.style.background='transparent';")
webView.evaluateJavaScript("window.BIHappyUsername") { username, error in
if (error == nil && String(describing: username) != "nil" && String(describing: username) != "Optional()" && String(describing: username) != "") {
self.user = String(describing: username!)
UserDefaults.standard.set("\(self.user)", forKey: "BIHappyAPIUser")
// print("User = \(self.user)")
}
}
webView.evaluateJavaScript("window.BIHappyAPIKey") { userToken, error in
if (error == nil) {
if (String(describing: userToken) != "Optional(NONE)" && String(describing: userToken) != "nil" && String(describing: userToken) != "Optional()" && String(describing: userToken) != "") {
if (String(describing: userToken) != "ERROR" && String(describing: userToken) != "DENIED") {
self.BIHappyToken = String(describing: userToken!)
self.BIHAPIisLoggedin = true
self.BIHAPILogin = true
} else {
self.BIHappyToken = String(describing: userToken!)
self.BIHAPIisLoggedin = false
self.BIHAPILogin = true
}
}
} else {
print("Unexpected error=\(String(describing: error))")
self.BIHappyToken = "ERROR"
self.BIHAPIisLoggedin = false
self.BIHAPILogin = true
}
}
}
open func webViewDidStartLoad(_ webView: UIWebView) {
}
open func webViewDidFinishLoad(_ webView: UIWebView) {
webView.stringByEvaluatingJavaScript(from: "document.body.style.background='transparent';")
let userName = webView.stringByEvaluatingJavaScript(from: "window.BIHappyUsername")
if (userName != "ERROR" && userName != "DENIED" && userName != "NONE") {
self.user = userName!
}
let userToken = webView.stringByEvaluatingJavaScript(from: "window.BIHappyAPIKey")
if (userToken != "ERROR" && userToken != "DENIED" && userToken != "NONE") {
self.BIHappyToken = userToken!
self.BIHAPIisLoggedin = true
self.BIHAPILogin = true
} else {
self.BIHappyToken = userToken!
self.BIHAPIisLoggedin = false
self.BIHAPILogin = true
}
}
open func log(_ t: Any) {
#if DEBUG
print("ℹ️️ \(t)")
#endif
}
fileprivate func BIApiGetAsText(_ from: String) -> String {
#if DEBUG
print("ℹ️️ Load URL: \(from)")
#endif
// if no key is registered, register last, or default api key!
if (!BIHappyKeyRegistered) {
// register key (last, or default api key)
self.registerKEY(self.apiKEY)
}
// if the string is a URL
if let myURL = URL(string: from) {
do {
// try to load it...
let myHTMLString = try NSString(contentsOf: myURL, encoding: String.Encoding.utf8.rawValue)
// convert to string and return
return myHTMLString as String
}
catch let error as NSError {
// shit a error
return "Error: \(error.localizedDescription)"
}
} else {
// this is no url?
return "Error: \(from) doesn't seems to be an URL"
}
}
open func getAllusers() -> Array<Any> {
// if no key is registered, register last, or default api key!
if (!BIHappyKeyRegistered) {
// register key (last, or default api key)
self.registerKEY(self.apiKEY)
}
let data = convertStringToDictionary(BIApiGetAsText("\(self.apiURL)/user/list"))
return (data?["data"])! as! Array<Any>
}
open func needToLogin() -> Bool {
// if no key is registered, register last, or default api key!
if (!BIHappyKeyRegistered) {
// register key (last, or default api key)
self.registerKEY(self.apiKEY)
}
// [BIHappyAPIToken: xxxxxxxxxxxxxx]
// [BIHappyAPIValid: YYYYMMDDHHmmss]
// YYYYMMDDHHIISS
let validTo = UserDefaults.standard.value(forKey: "BIHappyAPIValid") as! String? ?? "00000000000000"
let formatter = DateFormatter()
formatter.locale = Locale.current
formatter.dateFormat = "yyyyMMddHHmmss"
if (formatter.string(from: Date()) < validTo) {
// Seems valid. check & go.
let BIHappiTok = UserDefaults.standard.value(forKey: "BIHappyAPIToken") as! String? ?? "INVALID_TOKEN_FOR_USER" // Default api key?!
// Check URL
let checkAtURL = "\(apiURL)/check/token/token/\(BIHappiTok)"
// Is the token still valid?, if not nothing will work!
if (BIApiGetAsText(checkAtURL) == "VALID") {
// no need for login
return false
}
}
// user must re-login
return true
}
}
/**
**BIHappy Europe™** *API*
The official BIHappy Europe™ API
**Class:** DataStore
**Version:** 0.0.1
**Status:** Beta
*/
open class BIHappyDataStore {
static let sharedInstance = BIHappyDataStore()
open var currentUser: Any = ""
fileprivate init () { }
}