@@ -10,56 +10,27 @@ import Foundation
1010import UIKit
1111import Alamofire
1212
13−enum ResultR: Int {
14− case internalServerError = 500
15− case exceededContent = 470
16− case longContent = 471
17− case incorrectContent = 472
18− case impossibleContent = 473
19− case invalidTocken = 498
20− case alreadyRegistered = 409
21− case invalidCode = 403
22− case badAccess = 400
23− case tooMuchToAdd = 406
24− case notFound = 404
25− case success1 = 204
26− case success = 200
27−}
28−
2913class Model{
3014
3115 static let invalidTocken = 498
3216
33− static var hashTagTree: CompletionTree?
34−
3517 private static var isValidTocken: ((Int)->())? = { responce in
3618 print(responce)
3719 if responce == invalidTocken {
38−
3920 DataStorage.standard.setIsLoggedIn(value: false, with: 0)
4021 (UIApplication.shared.delegate as! AppDelegate).relaunch()
41−
42− Model.logout {
43− print("Logout Is Successful")
44− }
4522 }
4623 }
4724
4825 private static let baseUrl = "https://valera-denis.herokuapp.com"
4926 static let decoder = JSONDecoder()
50−
51− static let authMeURL = URL(string: "\(baseUrl)/authentication/me")!
52− static let deactivateURL = URL(string: "\(baseUrl)/deactivateAll")!
53− static let registerMeURL = URL(string: "\(baseUrl)/authentication/register")!
54− static let authVerifyURL = URL(string: "\(baseUrl)/authentication/verify")!
27+
5528 static let authenticationURL = URL(string:"\(baseUrl)/authentication/login")!
56− static let logOutURL = URL(string:"\(baseUrl)/authentication/logout")!
5729 static let postsLastURL = URL(string:"\(baseUrl)/posts/last")!
5830 static let postsForUserURL = URL(string:"\(baseUrl)/posts/forUser")!
5931 static let postsPublishURL = URL(string:"\(baseUrl)/posts/publish")!
6032 static let usersURL = URL(string:"\(baseUrl)/users")!
6133 static let usersAllURL = URL(string:"\(baseUrl)/users/all")!
62− static let usersUpdateURL = URL(string:"\(baseUrl)/users/update")!
6334 static let channelsGetURL = URL(string: "\(baseUrl)/channels/get")!
6435 static let channelsUpdateURL = URL(string: "\(baseUrl)/channels/update")!
6536 static let channelsListURL = URL(string: "\(baseUrl)/channels")!
@@ -67,21 +38,10 @@ class Model{
6738 static let channelsDeleteURL = URL(string: "\(baseUrl)/channels/delete")!
6839 static let channelsGetAnonURL = URL(string: "\(baseUrl)/channels/getAnonymous")!
6940 static let complexURL = URL(string: "\(baseUrl)/complex")!
70− static let hashTagTreeURL = URL(string: "\(baseUrl)/tags/completions")!
71− static let createGroupChatURL = URL(string: "\(baseUrl)/chats/createGroupChat")!
72− static let chatsGetAllURL = URL(string: "\(baseUrl)/chats/getAll")!
73− static let getGroupChatURL = URL(string: "\(baseUrl)/chats/getGroupChat")!
74− static let leaveGroupChatURL = URL(string: "\(baseUrl)/chats/leaveGroupChat")!
75− static let updateGroupChatURL = URL(string: "\(baseUrl)/chats/updateGroupChat")!
76− static let messagesGetGroupChatURL = URL(string: "\(baseUrl)/messages/get/groupChat")! //r
77− static let messagesSendURL = URL(string: "\(baseUrl)/messages/send")!
78− static let messagesGetUserChatURL = URL(string: "\(baseUrl)/messages/get/userChat")!
79− static let facultySearchURL = URL(string: "\(baseUrl)/faculty/search")!
80−
8141
82− struct QueryPosts<T: Codable>: Codable {
42+ struct QueryPosts: Codable {
8343 var users: [Int: Users]
84− var response: [T]
44+ var response: [Posts]
8545 }
8646
8747 struct Posts: Codable {
@@ -148,12 +108,7 @@ class Model{
148108 var lastName: String
149109 var firstName: String
150110 var id: Int
151− var faculty: Faculty
152− var email: String
153111
154− func fullName() -> String {
155− return "\(firstName) \(lastName)"
156− }
157112 }
158113
159114 struct Attachments: Codable {
@@ -175,7 +130,7 @@ class Model{
175130
176131 struct Channels: Codable {
177132
178− // static var fullTags = Set<String>()
133+ static var fullTags = Set<String>()
179134 static var fullPeople = [Users]()
180135 static var fullPeopleDict = [Int:Users]()
181136
@@ -213,108 +168,24 @@ class Model{
213168 }
214169 }
215170
216− struct AuthStatus: Codable {
217− var userStatus: String
218−
219− init(){
220− userStatus = "invalid"
221− }
222− }
223−
224− static func logout(completion: @escaping (()->())){
225− var request = URLRequest(url: logOutURL)
226− request.httpMethod = "POST"
171+ static func authenticate(with id: Int, completion: @escaping ((Bool)->())) {
227172
228− AF.request(request).response { (responce) in
229− isValidTocken?(responce.response?.statusCode ?? 498)
230−
231− if let code = responce.response?.statusCode, code == 498 {
232− return
233− }
234−
235− completion()
236− }
237− }
238−
239− /*
240− "email": "vchernyshev@hse.ru",
241− "middleName": "Algebrovich",
242− "lastName": "Leonidov",
243− "faculty": "cs.hse.ru/dse",
244− "firstName": "Seva"
245− */
246−
247− struct NewRegistration: Codable{
248− var email: String
249− var firstName: String?
250− var middleName: String?
251− var lastName: String?
252− var faculty: String?
253− }
254−
255− static func register(object: NewRegistration, completion: @escaping (()->())) {
256− var request = URLRequest(url: registerMeURL)
257− request.httpBody = try? JSONEncoder().encode(object)
173+ let json: [String:Any] = ["authenticationId" : id]
174+ let jsonData = try? JSONSerialization.data(withJSONObject: json)
258175
176+ var request = URLRequest(url: authenticationURL)
259177 request.httpMethod = "POST"
260− request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
261178
262− AF.request(request).response { (responce) in
263−
264− guard let code = responce.response?.statusCode else { return }
265− isValidTocken?(code)
266−
267− if let code = responce.response?.statusCode, code == 498 {
268− return
269− }
270−
271− if code == 204 {
272−
273− let fields = responce.response?.allHeaderFields as? [String :String]
274− let cookies = HTTPCookie.cookies(withResponseHeaderFields: fields!, for: responce.response!.url!)
275− HTTPCookieStorage.shared.setCookie(cookies[0])
276−
277− completion()
278− }
279− }
280− }
281−
282− // true only if everything is good
283− static func verify(with code: Int, completion: @escaping ((Bool)->())){
284− var request = URLRequest(url: authVerifyURL)
285− request.httpMethod = "POST"
286− request.httpBody = "\(code)".data(using: .utf8)
179+ // insert json data to the request
180+ request.httpBody = jsonData
287181 request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
288182
289183 AF.request(request).response { (responce) in
290184
291− guard let statusCode = responce.response?.statusCode else { completion(false); return }
292− isValidTocken?(statusCode)
293−
294− if let code = responce.response?.statusCode, code == 498 {
295− return
296− }
297−
298− if statusCode == 204 {
299− // at this point cookies are set
300− completion(true)
301− } else {
185+ guard let realResponse = responce.response, realResponse.statusCode == 200 else
186+ {
187+ print("Not a 200 response")
302188 completion(false)
303− }
304− }
305− }
306−
307− // yes or no
308− static func authenticateMe(completion: @escaping ((Bool)->())){
309− var request = URLRequest(url: authMeURL)
310− request.httpMethod = "POST"
311−
312− AF.request(request).response { (responce) in
313−
314− guard let statusCode = responce.response?.statusCode else { completion(false); return }
315− isValidTocken?(statusCode)
316−
317− if let code = responce.response?.statusCode, code == 498 {
318189 return
319190 }
320191
@@ -324,67 +195,26 @@ class Model{
324195 return
325196 }
326197
327− DataStorage.standard.setIsLoggedIn(value: true, with: personId)
328− completion(true)
329− }
330− }
331−
332− // register, ok or invalid
333− static func authenticate(with email: String, completion: @escaping ((AuthStatus)->())) {
334−
335− let json: [String:Any] = ["authenticationEmail" : email]
336− let jsonData = try? JSONSerialization.data(withJSONObject: json)
337−
338− var request = URLRequest(url: authenticationURL)
339− request.httpMethod = "POST"
340−
341− // insert json data to the request
342− request.httpBody = jsonData
343− request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
344−
345− AF.request(request).response { (response) in
198+ let fields = realResponse.allHeaderFields as? [String :String]
346199
347− guard let realResponse = response.response, realResponse.statusCode == 200 else
348− {
349− print("Not a 200 response")
350− completion(AuthStatus())
351− return
352− }
353−
354− guard let json = response.data else { return }
355− guard let res = try? decoder.decode(AuthStatus.self, from: json) else { return }
200+ let cookies = HTTPCookie.cookies(withResponseHeaderFields: fields!, for: realResponse.url!)
356201
357− if realResponse.statusCode == 200 && res.userStatus == "registered"
358− {
359− // at this point cookies are set
360− let fields = realResponse.allHeaderFields as? [String :String]
361− let cookies = HTTPCookie.cookies(withResponseHeaderFields: fields!, for: realResponse.url!)
362− HTTPCookieStorage.shared.setCookie(cookies[0])
363− }
202+ HTTPCookieStorage.shared.setCookie(cookies[0])
364203
365− completion(res)
204+ DataStorage.standard.setIsLoggedIn(value: true, with: personId)
205+ completion(true)
366206 }
367207 }
368208
369− struct GeneralRequest<T: Codable>: Codable
370− {
371− var direction: String
209+ struct PostsLastRequest: Codable {
372210 var limit: Int
373211 var exclusiveFrom: Int?
374− var request: T
375−
376− init(direction: String = "backward", limit: Int, exclusiveFrom: Int?, request: T) {
377− self.direction = direction
378− self.limit = limit
379− self.exclusiveFrom = exclusiveFrom
380− self.request = request
381− }
212+ var request: [Int] = []
382213
383214 enum CodingKeys: String, CodingKey {
384215 case limit
385216 case exclusiveFrom
386217 case request
387− case direction
388218 }
389219
390220 func encode(to encoder: Encoder) throws {
@@ -392,13 +222,12 @@ class Model{
392222 try container.encode(limit, forKey: .limit)
393223 try container.encode(exclusiveFrom, forKey: .exclusiveFrom)
394224 try container.encode(request, forKey: .request)
395− try container.encode(direction, forKey: .direction)
396225 }
397226 }
398227
399228 static func getLast(on limit: Int = 10, from pointInTime: Int? = nil, completion: @escaping (((users:[Int: Users], posts:[Posts]))->()))
400229 {
401− let postRequest = GeneralRequest<[Int]>(limit: limit, exclusiveFrom: pointInTime, request: [])
230+ let postRequest = PostsLastRequest(limit: limit, exclusiveFrom: pointInTime, request: [])
402231
403232 var request = URLRequest(url: postsLastURL)
404233 request.httpBody = try? JSONEncoder().encode(postRequest)
@@ -412,13 +241,9 @@ class Model{
412241
413242 isValidTocken?(response.response?.statusCode ?? 498)
414243
415− if let code = response.response?.statusCode, code == 498 {
416− return
417− }
418−
419244 guard let json = response.data else { return }
420245
421− guard let newQueery = try? decoder.decode(QueryPosts<Posts>.self, from: json) else { print("no")
246+ guard let newQueery = try? decoder.decode(QueryPosts.self, from: json) else { print("no")
422247 return }
423248
424249 idUser = newQueery.users
@@ -427,7 +252,7 @@ class Model{
427252 }
428253
429254
430− static func createAndPublish(body: [Attachments], tags: [String], completion: @escaping ((ResultR)->())){
255+ static func createAndPublish(body: [Attachments], tags: [String]){
431256 let jsonUpd = CreatedPost(body: body, tags: tags)
432257 var request = URLRequest(url: postsPublishURL)
433258
@@ -441,30 +266,17 @@ class Model{
441266 (response) in
442267
443268 isValidTocken?(response.response?.statusCode ?? 498)
444−
445− if let code = response.response?.statusCode, code == 498 {
446− return
447− }
448−
449− if let code = response.response?.statusCode,
450− let result = ResultR(rawValue: code)
451− {
452− completion(result)
453− } else {
454− completion(.internalServerError)
455− }
456269 }
457270 }
458271
459−// static func requestForPosts(limit: Int = 10, ){
460−//
461−// }
462272
463− static func getPostsForUser(for limit: Int = 10, from pointInTime: Int? = nil, with id: Int, completion: @escaping (([Posts])->()))
464− {
465− let postsRequest = GeneralRequest<Int>(limit: limit, exclusiveFrom: pointInTime, request: id)
273+ static func getPostsForUser(with id: Int, completion: @escaping (([Posts])->())){
274+ let json = [
275+ "request" : id,
276+ "limit": 10
277+ ]
466278
467− let jsonData = try? JSONEncoder().encode(postsRequest)
279+ let jsonData = try? JSONSerialization.data(withJSONObject: json)
468280
469281 var request = URLRequest(url: postsForUserURL)
470282 request.httpMethod = "POST"
@@ -478,13 +290,9 @@ class Model{
478290
479291 isValidTocken?(response.response?.statusCode ?? 498)
480292
481− if let code = response.response?.statusCode, code == 498 {
482− return
483− }
484−
485293 guard let json = response.data else { return }
486294
487− guard let newPost = try? decoder.decode(QueryPosts<Posts>.self, from: json) else { return }
295+ guard let newPost = try? decoder.decode(QueryPosts.self, from: json) else { return }
488296
489297 completion(newPost.response)
490298 }
@@ -494,7 +302,7 @@ class Model{
494302
495303 static func getUsers(for ids: [Int], completion: @escaping (([Int:Users])->())){
496304 let json = "\(Set(ids))"
497−
305+ print(json)
498306 var request = URLRequest(url: usersURL)
499307
500308 request.httpMethod = "POST"
@@ -508,16 +316,11 @@ class Model{
508316
509317 isValidTocken?(response.response?.statusCode ?? 498)
510318
511− if let code = response.response?.statusCode, code == 498 {
512− return
513− }
514−
515319 guard let json = response.data else { return }
516320
517321 guard let users = try? decoder.decode([Users].self, from: json) else { return }
518322
519323 var dict: [Int:Users] = [:]
520−
521324 users.forEach({ (user) in
522325 dict[user.id] = user
523326 })
@@ -527,10 +330,13 @@ class Model{
527330 }
528331
529332 // get channel (with id): in responce -- PostQuery
530− static func getChannel(with channelId: Int, on limit: Int = 10, from pointInTime: Int? = nil, completion: @escaping (((users:[Int: Users], posts:[Posts]))->()))
531− {
532− let postRequest = GeneralRequest<Int>(limit: limit, exclusiveFrom: pointInTime, request: channelId)
533− let jsonData = try? JSONEncoder().encode(postRequest)
333+ static func getChannel(with channelId: Int, completion: @escaping (((users:[Int: Users], posts:[Posts]))->())){
334+ let json = [
335+ "request" : channelId,
336+ "limit": 10
337+ ]
338+
339+ let jsonData = try? JSONSerialization.data(withJSONObject: json)
534340
535341 var request = URLRequest(url: channelsGetURL)
536342 request.httpMethod = "POST"
@@ -544,13 +350,10 @@ class Model{
544350
545351 isValidTocken?(response.response?.statusCode ?? 498)
546352
547− if let code = response.response?.statusCode, code == 498 {
548− return
549− }
550353
551354 guard let json = response.data else { return }
552355
553− guard let newQueery = try? decoder.decode(QueryPosts<Posts>.self, from: json) else { return }
356+ guard let newQueery = try? decoder.decode(QueryPosts.self, from: json) else { return }
554357
555358 idUser = newQueery.users
556359 completion((newQueery.users, newQueery.response))
@@ -558,7 +361,7 @@ class Model{
558361 }
559362
560363
561− static func createChannel(with channel: Channels, completion: @escaping ((ResultR)->())) {
364+ static func createChannel(with channel: Channels) {
562365
563366 var request = URLRequest(url: channelsCreateURL)
564367 request.httpMethod = "POST"
@@ -569,13 +372,6 @@ class Model{
569372 (response) in
570373
571374 isValidTocken?(response.response?.statusCode ?? 498)
572−
573− if let code = response.response?.statusCode, let result = ResultR(rawValue: code) {
574− completion(result)
575− return
576− }
577−
578− completion(ResultR.internalServerError)
579375 }
580376
581377 }
@@ -588,9 +384,6 @@ class Model{
588384 AF.request(request).responseJSON { (response) in
589385
590386 isValidTocken?(response.response?.statusCode ?? 498)
591− if let code = response.response?.statusCode, code == 498 {
592− return
593− }
594387
595388 guard let json = response.data else { return }
596389
@@ -609,9 +402,6 @@ class Model{
609402
610403 AF.request(request).response { (response) in
611404 isValidTocken?(response.response?.statusCode ?? 498)
612− if let code = response.response?.statusCode, code == 498 {
613− return
614− }
615405 }
616406 completion()
617407 }
@@ -627,9 +417,6 @@ class Model{
627417 (response) in
628418
629419 isValidTocken?(response.response?.statusCode ?? 498)
630− if let code = response.response?.statusCode, code == 498 {
631− return
632− }
633420 }
634421 }
635422
@@ -652,9 +439,6 @@ class Model{
652439 }
653440
654441 isValidTocken?(response.response?.statusCode ?? 498)
655− if let code = response.response?.statusCode, code == 498 {
656− return
657− }
658442 }
659443 }
660444
@@ -717,434 +501,27 @@ class Model{
717501 }
718502 }
719503 */
720− static func getAnonymousChannel(by anonymousChannel: Model.Channels, exclusiveFrom: Int? = nil, completion: @escaping (((users:[Int: Users], posts:[Posts]))->())){
504+ static func getAnonymousChannel(by anonymousChannel: Model.AnonymousChannel, completion: @escaping (((users:[Int: Users], posts:[Posts]))->())){
721505
722− let req = GeneralRequest<Model.Channels>(limit: 10, exclusiveFrom: exclusiveFrom, request: anonymousChannel)
723−
724506 var request = URLRequest(url: channelsGetAnonURL)
725507 request.httpMethod = "POST"
726− request.httpBody = try? JSONEncoder().encode(req)
508+ request.httpBody = try? JSONEncoder().encode(anonymousChannel)
727509
728510 request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
729511 AF.request(request).response {
730512 (response) in
731513
732514 isValidTocken?(response.response?.statusCode ?? 498)
733− if let code = response.response?.statusCode, code == 498 {
734− return
735− }
736−
737− guard let json = response.data else { return }
738−
739− guard let newQueery = try? decoder.decode(QueryPosts<Posts>.self, from: json) else { return }
740− completion((newQueery.users, newQueery.response))
741− }
742− }
743−
744− static func getCompl(completion: @escaping ((CompletionTree)->())) {
745−
746− AF.request(URLRequest(url: hashTagTreeURL)).responseJSON {
747− (response) in
748− isValidTocken?(response.response?.statusCode ?? 498)
749− if let code = response.response?.statusCode, code == 498 {
750− return
751− }
752− guard let json = response.data else { return }
753− guard let tree = try? decoder.decode(CompletionTree.self, from: json) else { return }
754− completion(tree)
755− }
756− }
757−
758− static func getChatAll(limit: Int = 10, exclusiveFrom: Int? = nil, request: [Int] = [], completion: @escaping ((([Dialog],[Int:Model.Users]))->()))
759− {
760− let req = GeneralRequest<[Int]>(limit: limit, exclusiveFrom: exclusiveFrom, request: request)
761− var request = URLRequest(url: chatsGetAllURL)
762− request.httpMethod = "POST"
763− request.httpBody = try? JSONEncoder().encode(req)
764− request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
765−
766− AF.request(request).responseJSON { response in
767− isValidTocken?(response.response?.statusCode ?? 498)
768−
769− if let code = response.response?.statusCode, code == 498 {
770− return
771− }
772−
773− guard let json = response.data else { return }
774− let dialogs = try! decoder.decode(QueryPosts<Dialog>.self, from: json)
775−
776− completion((dialogs.response,dialogs.users))
777− }
778− }
779−
780− enum Dialog: Codable
781− {
782− case groupChat(GroupChat)
783− case userChat(UserChat)
784−
785− private enum DialogKeys: CodingKey{
786− case groupChat
787− case userChat
788− }
789−
790− init(from decoder: Decoder) throws {
791− let container = try decoder.container(keyedBy: DialogKeys.self)
792− if container.contains(.groupChat){
793− self = .groupChat(try GroupChat(from: container.superDecoder(forKey: .groupChat)))
794− } else if container.contains(.userChat){
795− self = .userChat(try UserChat(from: container.superDecoder(forKey: .userChat)))
796− } else {
797− throw DecodingError.keyNotFound(DialogKeys.groupChat, DecodingError.Context(codingPath: container.codingPath, debugDescription: "hz"))
798− }
799− }
800−
801− func encode(to encoder: Encoder) throws {
802− var container = encoder.container(keyedBy: DialogKeys.self)
803− switch self{
804− case .groupChat(let chat):
805− try chat.encode(to: container.superEncoder(forKey: .groupChat))
806− case .userChat(let chat):
807− try chat.encode(to: container.superEncoder(forKey: .userChat))
808− }
809− }
810− }
811−
812− struct GroupChat: Codable {
813− var group: Group
814− var lastMessage: LastMessage?
815−
816−
817− init(group: Group, lastMessage: LastMessage? = nil) {
818− self.group = group
819− self.lastMessage = lastMessage
820− }
821− }
822−
823− struct UserChat: Codable {
824− var user: Int
825− var lastMessage: LastMessage?
826−
827− init(user: Int, lastMessage: LastMessage? = nil) {
828− self.user = user
829− self.lastMessage = lastMessage
830− }
831− }
832−
833− struct Group: Codable {
834− var users: [Int: UserPermission]
835− var name: String
836− var id: Int
837−
838− init(users: [Int: UserPermission] = [:], name: String = "", id: Int) {
839− self.id = id
840− self.users = users
841− self.name = name
842− }
843− }
844−
845− struct UserPermission: Codable {
846− var isAdmin: Bool
847− }
848−
849− struct LastMessage: Codable {
850− var body: Attachments
851− var destination: MessageDestination
852− var time: String
853− var author: Int
854− var id: Int
855−
856− enum MessageCodingKeys: CodingKey{
857− case user
858− case group
859− case body
860− case time
861− case author
862− case id
863− }
864−
865− init(from decoder: Decoder) throws
866− {
867− let container = try decoder.container(keyedBy: MessageCodingKeys.self)
868− time = try container.decode(String.self, forKey: .time)
869− body = try container.decode(Attachments.self, forKey: .body)
870− author = try container.decode(Int.self, forKey: .author)
871− id = try container.decode(Int.self, forKey: .id)
872−
873− if container.contains(.user){
874− destination = MessageDestination.userChatDestination(try Int(from: container.superDecoder(forKey: .user)))
875− } else if container.contains(.group){
876− destination = MessageDestination.groupChatDestination(try Int(from: container.superDecoder(forKey: .group)))
877− } else {
878− throw DecodingError.keyNotFound(MessageCodingKeys.group, DecodingError.Context(codingPath: container.codingPath, debugDescription: "hz gr"))
879− }
880− }
881−
882− func encode(to encoder: Encoder) throws {
883− var container = encoder.container(keyedBy: MessageCodingKeys.self)
884−
885− try container.encode(time, forKey: .time)
886− try container.encode(id, forKey: .id)
887− try container.encode(author, forKey: .author)
888− try container.encode(body, forKey: .body)
889−
890− switch destination {
891− case .userChatDestination(let uId):
892− try uId.encode(to: container.superEncoder(forKey: .user))
893− case .groupChatDestination(let gId):
894− try gId.encode(to: container.superEncoder(forKey: .group))
895− }
896− }
897− }
898−
899− enum MessageDestination: Codable
900− {
901− func encode(to encoder: Encoder) throws
902− {
903− var container = encoder.container(keyedBy: MessCodingKeys.self)
904− switch self {
905− case .userChatDestination(let uId):
906− try uId.encode(to: container.superEncoder(forKey: .user))
907− case .groupChatDestination(let gId):
908− try gId.encode(to: container.superEncoder(forKey: .group))
909− }
910− }
911−
912− init(from decoder: Decoder) throws
913− {
914− let container = try decoder.container(keyedBy: MessCodingKeys.self)
915− if container.contains(.user){
916− self = .userChatDestination(try Int(from: container.superDecoder(forKey: .user)))
917− } else if container.contains(.group){
918− self = .groupChatDestination(try Int(from: container.superDecoder(forKey: .group)))
919− } else {
920− throw DecodingError.keyNotFound(MessCodingKeys.group, DecodingError.Context(codingPath: container.codingPath, debugDescription: "hz gr"))
921− }
922− }
923−
924− enum MessCodingKeys: CodingKey{
925− case user
926− case group
927− }
928−
929− case userChatDestination(Int)
930− case groupChatDestination(Int)
931−
932− }
933−
934− static func createGroupChat(from group: Group, completion: @escaping ((Int)->())) {
935− let req = group
936− var request = URLRequest(url: createGroupChatURL)
937− request.httpMethod = "POST"
938− request.httpBody = try? JSONEncoder().encode(req)
939− request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
940−
941− AF.request(request).response { (response) in
942−
943− isValidTocken?(response.response?.statusCode ?? 498)
944− if let code = response.response?.statusCode, code == 498 {
945− return
946− }
947515
948516 guard let json = response.data else { return }
949− let stringInt = String.init(data: json, encoding: String.Encoding.utf8)
950− let intId = Int.init(stringInt!)
951517
952− completion(intId!)
953− }
954− }
955−
956− static func getMessagesFor(typeOfChat: Model.Dialog, chat id: Int, exclusiveFrom: Int? = nil, limit l: Int = 25, direction: String = "backward", completion: @escaping (([LastMessage])->()))
957− {
958− let req = GeneralRequest<Int>(direction: direction, limit: l, exclusiveFrom: exclusiveFrom, request: id)
959− var request: URLRequest?
960−
961− switch typeOfChat {
962− case .groupChat:
963− request = URLRequest(url: messagesGetGroupChatURL)
964− case .userChat:
965− request = URLRequest(url: messagesGetUserChatURL)
966− }
967−
968− request!.httpMethod = "POST"
969− request!.httpBody = try? JSONEncoder().encode(req)
970− request!.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
971−
972− AF.request(request!).response { (response) in
973−
974− isValidTocken?(response.response?.statusCode ?? 498)
975− if let code = response.response?.statusCode, code == 498 {
976− return
977− }
518+ guard let newQueery = try? decoder.decode(QueryPosts.self, from: json) else { return }
978519
979− guard let json = response.data else { return }
980− guard let messages = try? decoder.decode([LastMessage].self, from: json) else { return }
981−
982− completion(messages)
983− }
984− }
985−
986− static func leaveGroupChat(id: Int, completion: @escaping (()->()))
987− {
988− var request = URLRequest(url: leaveGroupChatURL)
989− request.httpMethod = "POST"
990− request.httpBody = "\(id)".data(using: .utf8)
991− request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
992−
993− AF.request(request).response { (response) in
994− isValidTocken?(response.response?.statusCode ?? 498)
995−
996− if let code = response.response?.statusCode, code == 498 {
997− return
998− }
999− }
1000−
1001− completion()
1002− }
1003−
1004− static func updateGroupChat(with group: Model.Group)
1005− {
1006− var request = URLRequest(url: updateGroupChatURL)
1007− request.httpMethod = "POST"
1008− request.httpBody = try? JSONEncoder().encode(group)
1009− request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
1010−
1011− AF.request(request).response { (response) in
1012− isValidTocken?(response.response?.statusCode ?? 498)
1013−
1014− if let code = response.response?.statusCode, code == 498 {
1015− return
1016− }
1017− }
1018−
1019− // completion()
1020− }
1021−
1022− struct SendMessage: Codable {
1023− var body: Attachments
1024− var destination: MessageDestination
1025−
1026− init(from decoder: Decoder) throws
1027− {
1028− let container = try decoder.container(keyedBy: LastMessage.MessageCodingKeys.self)
1029− body = try container.decode(Attachments.self, forKey: .body)
1030−
1031− if container.contains(.user){
1032− destination = MessageDestination.userChatDestination(try Int(from: container.superDecoder(forKey: .user)))
1033− } else if container.contains(.group){
1034− destination = MessageDestination.groupChatDestination(try Int(from: container.superDecoder(forKey: .group)))
1035− } else {
1036− throw DecodingError.keyNotFound(LastMessage.MessageCodingKeys.group, DecodingError.Context(codingPath: container.codingPath, debugDescription: "hz gr1"))
1037− }
1038− }
1039−
1040− func encode(to encoder: Encoder) throws {
1041− var container = encoder.container(keyedBy: LastMessage.MessageCodingKeys.self)
1042− try container.encode(body, forKey: .body)
1043−
1044− switch destination {
1045− case .userChatDestination(let uId):
1046− try uId.encode(to: container.superEncoder(forKey: .user))
1047− case .groupChatDestination(let gId):
1048− try gId.encode(to: container.superEncoder(forKey: .group))
1049− }
1050− }
1051−
1052− init(body: Attachments, destination: MessageDestination)
1053− {
1054− self.body = body
1055− self.destination = destination
1056− }
1057− }
1058−
1059− static func sendMessage(message: SendMessage, completion: @escaping ((ResultR)->())){
1060−
1061− var request = URLRequest(url: messagesSendURL)
1062− request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
1063− request.httpMethod = "POST"
1064− request.httpBody = try? JSONEncoder().encode(message)
1065−
1066− AF.request(request).response { (response) in
1067− isValidTocken?(response.response?.statusCode ?? 498)
1068−
1069− if let code = response.response?.statusCode, code == 498 {
1070− return
1071− }
1072−
1073− if let result = ResultR(rawValue: response.response!.statusCode){
1074− completion(result)
1075− } else {
1076− completion(.internalServerError)
1077− }
520+ // idUser = newQueery.users
521+ completion((newQueery.users, newQueery.response))
1078522 }
1079523 }
1080524
1081− struct Faculty: Codable
1082− {
1083−
1084− var path: String
1085− var url: String
1086− var campusName: String
1087− var campusCode: String
1088− var name: String
1089− var tags: [String]
1090− var address: String
1091−
1092− }
1093−
1094− static func searchFaculty(string: String, completion: @escaping (([Model.Faculty])->()))
1095− {
1096− var request = URLRequest(url: facultySearchURL)
1097− request.httpMethod = "POST"
1098− request.httpBody = string.data(using: .utf8)
1099− request.setValue("text/plain;charset=utf-8", forHTTPHeaderField: "Content-Type")
1100−
1101− AF.request(request).response { (response) in
1102− isValidTocken?(response.response?.statusCode ?? 498)
1103−
1104− if let code = response.response?.statusCode, code == 498 {
1105− return
1106− }
1107−
1108− guard let json = response.data else { return }
1109− guard let faculties = try? decoder.decode([Faculty].self, from: json) else { return }
1110525
1111− completion(faculties)
1112− }
1113− }
1114526
1115− static func userUpdate(with newUser: NewRegistration, completion: @escaping ((Bool)->())) {
1116− var request = URLRequest(url: usersUpdateURL)
1117− request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
1118− request.httpMethod = "POST"
1119− request.httpBody = try? JSONEncoder().encode(newUser)
1120−
1121− AF.request(request).response { (response) in
1122− isValidTocken?(response.response?.statusCode ?? 498)
1123−
1124− if let code = response.response?.statusCode, code == 498 {
1125− return
1126− }
1127−
1128− if let code = response.response?.statusCode, code != 204{
1129− completion (false)
1130− } else {
1131− completion(true)
1132− }
1133− }
1134− }
1135−
1136− static func deactivateAll(completion: @escaping (()->())){
1137− var request = URLRequest(url: deactivateURL)
1138− request.httpMethod = "DELETE"
1139−
1140− AF.request(request).response { (responce) in
1141− isValidTocken?(responce.response?.statusCode ?? 498)
1142−
1143− if let code = responce.response?.statusCode, code == 498 {
1144− return
1145− }
1146−
1147− completion()
1148− }
1149− }
1150527}