SHARE
TWEET

Untitled

a guest Dec 13th, 2016 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //
  2. //  PerfectHandler.swift
  3. //  WebServiceProject
  4. //
  5. //  Created by Marco Cruz on 20/07/16.
  6. //  Copyright © 2016 Marco Cruz. All rights reserved.
  7. //
  8.  
  9.  
  10. import AVFoundation
  11. import PerfectLib
  12. import AVKit
  13. import MySQL
  14.  
  15. let HOST = "localhost"
  16. let USER = "root"
  17. let PASSWORD = "1234"
  18. let DB_NAME = "OpinionShare"
  19.  
  20. typealias TrimCompletion = (NSError?) -> ()
  21. typealias TrimPoints = [(CMTime, CMTime)]
  22.  
  23. var videoStatus: String?
  24. var videoStartTime: NSDate?
  25. var pushNotificationsHandler = PushNotificationsHandler()
  26.  
  27. //////////////////////// MYSQL CONNECTION ////////////////////////
  28. func createDatabase() {
  29.     let mysql = MySQL()
  30.     let connected = mysql.connect(HOST, user: USER, password: PASSWORD)
  31.    
  32.     guard connected else { print(mysql.errorMessage()); return }
  33.    
  34.     defer { mysql.close() }
  35.    
  36.     var isDatabase = mysql.selectDatabase(DB_NAME)
  37.     if !isDatabase {
  38.         isDatabase = mysql.query("CREATE DATABASE \(DB_NAME);")
  39.     }
  40.    
  41.     //Users
  42.     let isTableUsers = mysql.query("CREATE TABLE IF NOT EXISTS Users (user_id INT(8) UNSIGNED AUTO_INCREMENT PRIMARY KEY, first_name TEXT NOT NULL, last_name TEXT NOT NULL);")
  43.    
  44.     //Matches
  45.     let isTableMatches = mysql.query("CREATE TABLE IF NOT EXISTS Matches (match_id INT(8) UNSIGNED AUTO_INCREMENT PRIMARY KEY, home TEXT NOT NULL, visitor TEXT NOT NULL, home_score INT(8) UNSIGNED, visitor_score INT(8) UNSIGNED, status TEXT NOT NULL);")
  46.    
  47.     //Moments
  48.     let isTableMoments = mysql.query("CREATE TABLE IF NOT EXISTS Moments (moment_id INT(8) UNSIGNED AUTO_INCREMENT PRIMARY KEY, user_id INT(8) UNSIGNED, match_id INT(8) UNSIGNED, time TEXT NOT NULL, FOREIGN KEY (user_id) REFERENCES Users(user_id),  FOREIGN KEY (match_id) REFERENCES Matches(match_id));")
  49.    
  50.     //Responses
  51.     let isTableResponses = mysql.query("CREATE TABLE IF NOT EXISTS Responses (response_id INT(8) UNSIGNED AUTO_INCREMENT PRIMARY KEY, moment_id INT(8) UNSIGNED, user_id INT(8) UNSIGNED, opinion TEXT NOT NULL, emotion TEXT NOT NULL, FOREIGN KEY (moment_id) REFERENCES Moments(moment_id), FOREIGN KEY (user_id) REFERENCES Users(user_id));")
  52.    
  53.     guard isDatabase && isTableUsers && isTableMatches && isTableMoments && isTableResponses else {
  54.         print(mysql.errorMessage()); return
  55.     }
  56. }
  57.  
  58.  
  59. public func PerfectServerModuleInit(){
  60.    
  61.     Routing.Handler.registerGlobally()
  62.    
  63.     Routing.Routes["GET", "/startvideo"] = { _ in return StartVideo() }
  64.     Routing.Routes["GET", "/videotimer"] = { _ in return GetVideoTimer() }
  65.     Routing.Routes["GET", "/videostatus"] = { _ in return GetVideoStatus() }
  66.     Routing.Routes["GET", "/video.mp4"] = { _ in return GetVideo() }
  67.     Routing.Routes["GET", "/test"] = { _ in return GetTest() }
  68.     Routing.Routes["POST", "/postuser"] = { _ in return PostUser() }
  69.     Routing.Routes["POST", "/postmoment"] = { _ in return PostMoment() }
  70.     Routing.Routes["POST", "/postresponse"] = { _ in return PostResponse() }
  71.     Routing.Routes["GET", "/matches"] = { _ in return GetMatches() }
  72.     Routing.Routes["GET", "/moments"] = { _ in return GetMoments() }
  73.     Routing.Routes["GET", "/responses"] = { _ in return GetResponses() }
  74.     Routing.Routes["GET", "/opinions"] = { _ in return GetOpinions() }
  75.     Routing.Routes["GET", "/emotions"] = { _ in return GetEmotions() }
  76.     Routing.Routes["GET", "/friendsreactions"] = { _ in return GetFriendsReactions() }
  77.     Routing.Routes["GET", "/thumbnail"] = { _ in return GetThumbnail() }
  78.    
  79.     createDatabase()
  80.     pushNotificationsHandler.start()
  81.     pushNotificationsHandler.sendNotification()
  82.     videoStatus = "offline"
  83. }
  84.  
  85.  
  86. func resultsToJSON(results results: MySQL.Results, _ fields: [String]) -> String? {
  87.     if results.numFields() != fields.count { return nil }
  88.    
  89.     let encoder = JSONEncoder()
  90.     var rowValues = [[String: JSONValue]]()
  91.    
  92.     results.forEachRow{ row in
  93.         var rowValue = [String: JSONValue]()
  94.         for c in 0 ..< fields.count {
  95.             rowValue[fields[c]] = row[c]
  96.         }
  97.         rowValues.append(rowValue)
  98.     }
  99.    
  100.     var responseString = "["
  101.    
  102.     do {
  103.         for c in 0 ..< rowValues.count {
  104.             let rowJSON = try encoder.encode(rowValues[c])
  105.             responseString += rowJSON
  106.             if c != rowValues.count - 1 { responseString += "," }
  107.             else { responseString += "]" }
  108.         }
  109.         return responseString
  110.     } catch {
  111.         return nil
  112.     }
  113. }
  114.  
  115. class GetVideo: RequestHandler {
  116.     func handleRequest(request: WebRequest, response: WebResponse) {
  117.        
  118.         let milliseconds = request.param("milliseconds")
  119.        
  120.         let docRoot = "/Users/marcocruz/Desktop/XCode 7/Server"
  121.         do {
  122.             let trimmedVideo = File("\(docRoot)/Video\(milliseconds!).mp4")
  123.             let videoSize = trimmedVideo.size()
  124.             let videoBytes = try trimmedVideo.readSomeBytes(videoSize)
  125.             response.addHeader("Accept-Ranges", value: "bytes")
  126.             response.addHeader("Content-Length", value: "\(videoSize)")
  127.             response.addHeader("Content-Type", value: "video/mp4")
  128.             response.addHeader("Age", value: "100000")
  129.             response.addHeader("Connection", value: "close")
  130.             response.addHeader("Strict-Transport-Security", value: "max-age=15552000")
  131.             response.addHeader("X-Cache", value: "HIT")
  132.             response.addHeader("Cache-Control", value: "max-age=604800")
  133.            
  134.             response.appendBodyBytes(videoBytes)
  135.         } catch {
  136.             response.appendBodyString("Error handling request: \(error)")
  137.         }
  138.         response.requestCompletedCallback()
  139.  
  140.     }
  141. }
  142.  
  143.  
  144. class GetThumbnail: RequestHandler {
  145.     func handleRequest(request: WebRequest, response: WebResponse) {
  146.         let milliseconds : Int!
  147.         milliseconds = Int(request.param("milliseconds")!)
  148.        
  149.        
  150.         let docRoot = "/Users/marcocruz/Desktop/XCode 7/Server/Thumbnails"
  151.         do {
  152.             let img = File("\(docRoot)/\(milliseconds).jpeg")
  153.             let imageSize = img.size()
  154.             let imageBytes = try img.readSomeBytes(imageSize)
  155.             response.replaceHeader("contentType", value: "image/jpeg")
  156.             response.appendBodyBytes(imageBytes)
  157.         } catch {
  158.             response.appendBodyString("Error handling request: \(error)")
  159.         }
  160.         response.requestCompletedCallback()
  161.     }
  162. }
  163.  
  164.  
  165. func verifyPresetForAsset(preset: String, asset: AVAsset) -> Bool
  166. {
  167.     let compatiblePresets = AVAssetExportSession.exportPresetsCompatibleWithAsset(asset)
  168.     let filteredPresets = compatiblePresets.filter { $0 == preset }
  169.     return filteredPresets.count > 0 || preset == AVAssetExportPresetPassthrough
  170. }
  171.  
  172. func removeFileAtURLIfExists(url: NSURL)
  173. {
  174.     if let filePath = url.path {
  175.         let fileManager = NSFileManager.defaultManager()
  176.         if fileManager.fileExistsAtPath(filePath) {
  177.             do {
  178.                 try fileManager.removeItemAtPath(filePath)
  179.             } catch {
  180.                 NSLog("Couldn't remove existing destination file")
  181.             }
  182.         }
  183.     }
  184. }
  185.  
  186.  
  187. func trimVideo(sourceURL: NSURL, destinationURL: NSURL, trimPoints: TrimPoints, completion: TrimCompletion?)
  188. {
  189.     assert(sourceURL.fileURL)
  190.     assert(destinationURL.fileURL)
  191.    
  192.     let options = [ AVURLAssetPreferPreciseDurationAndTimingKey: true ]
  193.     let asset = AVURLAsset(URL: sourceURL, options: options)
  194.     let preferredPreset = AVAssetExportPresetPassthrough
  195.     if verifyPresetForAsset(preferredPreset, asset: asset)
  196.     {
  197.         let composition = AVMutableComposition()
  198.         let videoCompTrack = composition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID())
  199.         let audioCompTrack = composition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())
  200.         let assetVideoTrack: AVAssetTrack = asset.tracksWithMediaType(AVMediaTypeVideo).first as AVAssetTrack!
  201.         let assetAudioTrack: AVAssetTrack = asset.tracksWithMediaType(AVMediaTypeAudio).first as AVAssetTrack!
  202.         var compError: NSError?
  203.         var accumulatedTime = kCMTimeZero
  204.        
  205.         for (startTimeForCurrentSlice, endTimeForCurrentSlice) in trimPoints {
  206.             let durationOfCurrentSlice = CMTimeSubtract(endTimeForCurrentSlice, startTimeForCurrentSlice)
  207.             let timeRangeForCurrentSlice = CMTimeRangeMake(startTimeForCurrentSlice, durationOfCurrentSlice)
  208.            
  209.             do {
  210.                 try videoCompTrack.insertTimeRange(timeRangeForCurrentSlice, ofTrack: assetVideoTrack, atTime: accumulatedTime)
  211.             } catch {}
  212.             do {
  213.                 try audioCompTrack.insertTimeRange(timeRangeForCurrentSlice, ofTrack: assetAudioTrack, atTime: accumulatedTime)
  214.             } catch {}
  215.            
  216.            
  217.             if compError != nil {
  218.                 NSLog("error during composition: \(compError)")
  219.                 if let completion = completion {
  220.                     completion(compError)
  221.                 }
  222.             }
  223.            
  224.             accumulatedTime = CMTimeAdd(accumulatedTime, durationOfCurrentSlice)
  225.         }
  226.        
  227.         let exportSession = AVAssetExportSession(asset: composition, presetName: preferredPreset)
  228.         exportSession!.outputURL = destinationURL
  229.         exportSession!.outputFileType = AVFileTypeAppleM4V
  230.         exportSession!.shouldOptimizeForNetworkUse = true
  231.        
  232.         removeFileAtURLIfExists(destinationURL)
  233.        
  234.         exportSession!.exportAsynchronouslyWithCompletionHandler({ () -> Void in
  235.             if let completion = completion {
  236.                 completion(exportSession!.error)
  237.             }
  238.         })
  239.     } else {
  240.         NSLog("Could not find a suitable export preset for the input video")
  241.         let error = NSError(domain: "", code: -1, userInfo: nil)
  242.         if let completion = completion {
  243.             completion(error)
  244.         }
  245.     }
  246. }
  247.  
  248.  
  249. class GetTest: RequestHandler {
  250.     func handleRequest(request: WebRequest, response: WebResponse) {
  251.         response.appendBodyString("TESTE")
  252.         response.setStatus(200, message: "Success!")
  253.         response.requestCompletedCallback()
  254.     }
  255. }
  256.  
  257. class StartVideo: RequestHandler {
  258.     func handleRequest(request: WebRequest, response: WebResponse) {
  259.        
  260.         videoStartTime = NSDate();
  261.         videoStatus = "online";
  262.         response.setStatus(200, message: "Success!")
  263.         response.requestCompletedCallback()
  264.     }
  265. }
  266.  
  267. class GetVideoTimer: RequestHandler {
  268.     func handleRequest(request: WebRequest, response: WebResponse) {
  269.        
  270.         var timer: Int!
  271.         timer = getMiliseconds(NSDate()) - getMiliseconds(videoStartTime!)
  272.         response.setStatus(200, message: "Success!")
  273.         response.requestCompletedCallback()
  274.     }
  275. }
  276.  
  277. class GetVideoStatus: RequestHandler {
  278.     func handleRequest(request: WebRequest, response: WebResponse) {
  279.        
  280.         response.appendBodyString(videoStatus!)
  281.         response.setStatus(200, message: "Success!")
  282.         response.requestCompletedCallback()
  283.     }
  284. }
  285.  
  286. class PostUser: RequestHandler {
  287.     func handleRequest(request: WebRequest, response: WebResponse) {
  288.        
  289.         let params = request.postParams
  290.         guard params.count == 3 else {
  291.             response.setStatus(400, message: "Wrong params!")
  292.             response.requestCompletedCallback(); return
  293.         }
  294.         let first_name : String!
  295.         first_name = String(request.param("firstname")!)
  296.         let last_name : String!
  297.         last_name = String(request.param("lastname")!)
  298.         let device_token : String!
  299.         device_token = String(request.param("device_token")!)
  300.        
  301.         let mysql = MySQL()
  302.         let connected = mysql.connect(HOST, user: USER, password: PASSWORD)
  303.        
  304.         guard connected else {
  305.             print(mysql.errorMessage())
  306.             response.setStatus(500, message: "Couldn't connect to database")
  307.             response.requestCompletedCallback(); return
  308.         }
  309.        
  310.         mysql.selectDatabase(DB_NAME)
  311.         let querySuccess = mysql.query("SELECT * FROM Users WHERE first_name = '\(first_name)' AND last_name = '\(last_name)';")
  312.         guard querySuccess else {
  313.             print(mysql.errorMessage())
  314.             response.setStatus(500, message: "Something went wrong")
  315.             response.requestCompletedCallback(); return
  316.         }
  317.        
  318.         var results: MySQL.Results!
  319.         results = mysql.storeResults()
  320.        
  321.         if(results.numRows() == 0){
  322.             let querySuccess2 = mysql.query("INSERT INTO Users (first_name, last_name, device_token) VALUES ('\(first_name)', '\(last_name)', '\(device_token)');")
  323.             guard querySuccess2 else {
  324.                 print(mysql.errorMessage())
  325.                 response.setStatus(500, message: "Something went wrong")
  326.                 response.requestCompletedCallback(); return
  327.             }
  328.         }else{
  329.             let querySuccess2 = mysql.query("UPDATE Users SET device_token = '\(device_token)' WHERE first_name = '\(first_name)' AND last_name = '\(last_name)';")
  330.             guard querySuccess2 else {
  331.                 print(mysql.errorMessage())
  332.                 response.setStatus(500, message: "Something went wrong")
  333.                 response.requestCompletedCallback(); return
  334.             }
  335.         }
  336.        
  337.         let querySuccess3 = mysql.query("SELECT user_id, first_name, last_name FROM Users WHERE first_name = '\(first_name)' AND last_name = '\(last_name)';")
  338.        
  339.         guard querySuccess3 else {
  340.             print(mysql.errorMessage())
  341.             response.setStatus(500, message: "Something went wrong")
  342.             response.requestCompletedCallback(); return
  343.         }
  344.        
  345.         var results2: MySQL.Results!
  346.         results2 = mysql.storeResults()
  347.    
  348.         guard results2.numRows() != 0 else {
  349.             response.setStatus(500, message: "User wansn't saved in the database.")
  350.             response.appendBodyString("User wansn't saved in the database.")
  351.             response.requestCompletedCallback(); return
  352.         }
  353.  
  354.         let result = resultsToJSON(results: results2!, ["user_id", "first_name", "last_name"])
  355.         guard result != nil else {
  356.             print("json encoding did not work very well... or at all")
  357.             response.setStatus(500, message: "no goo json encoding oops")
  358.             response.requestCompletedCallback(); return
  359.         }
  360.    
  361.         response.appendBodyString(result!)
  362.         print("User: \(first_name), \(last_name), \(device_token)");
  363.         response.setStatus(201, message: "post success")
  364.         response.requestCompletedCallback()
  365.     }
  366. }
  367.  
  368.  
  369. class PostMoment: RequestHandler {
  370.     func handleRequest(request: WebRequest, response: WebResponse) {
  371.        
  372.         let params = request.postParams
  373.         guard params.count == 5 else {
  374.             response.setStatus(400, message: "Wrong params!")
  375.             response.requestCompletedCallback(); return
  376.         }
  377.         let user_id : Int!
  378.         user_id = Int(request.param("userid")!)
  379.         let match_id : Int!
  380.         match_id = Int(request.param("matchid")!)
  381.         let compensation : Int!
  382.         compensation = Int(request.param("compensation")!)
  383.         let opinion : String!
  384.         opinion = request.param("opinion")!
  385.         let emotion : String!
  386.         emotion = request.param("emotion")!
  387.        
  388.         let timer = (getMiliseconds(NSDate()) - getMiliseconds(videoStartTime!) - compensation)
  389.         let time: String!
  390.         time = timer.msToSeconds.minuteSecondMS
  391.        
  392.         let mysql = MySQL()
  393.         let connected = mysql.connect(HOST, user: USER, password: PASSWORD)
  394.        
  395.         guard connected else {
  396.             print(mysql.errorMessage())
  397.             response.setStatus(500, message: "Couldn't connect to database")
  398.             response.requestCompletedCallback(); return
  399.         }
  400.        
  401.         mysql.selectDatabase(DB_NAME)
  402.         let querySuccess = mysql.query("INSERT INTO Moments (user_id, match_id, time) VALUES ('\(user_id)', '\(match_id)', '\(time)');")
  403.         guard querySuccess else {
  404.             print(mysql.errorMessage())
  405.             response.setStatus(500, message: "Something went wrong")
  406.             response.requestCompletedCallback(); return
  407.         }
  408.        
  409.         mysql.query("SET @last_id_in_Moments = LAST_INSERT_ID();")
  410.        
  411.         let querySuccess3 = mysql.query("INSERT INTO Responses (moment_id, user_id, opinion, emotion) VALUES (@last_id_in_Moments, '\(user_id)', '\(opinion)', '\(emotion)');")
  412.  
  413.         guard querySuccess3 else {
  414.             print(mysql.errorMessage())
  415.             response.setStatus(500, message: "Something went wrong")
  416.             response.requestCompletedCallback(); return
  417.         }
  418.        
  419.         dispatch_async(dispatch_get_main_queue(),{
  420.            
  421.             self.saveVideo(timer)
  422.            
  423.         })
  424.        
  425.  
  426.         //pushNotificationsHandler.sendNotification()
  427.         print("New moment: \(user_id), \(match_id), \(opinion), \(emotion), \(time)");
  428.         response.setStatus(200, message: "post success")
  429.         response.requestCompletedCallback()
  430.     }
  431.    
  432.    
  433.    
  434.     func saveVideo(milliseconds: Int)
  435.     {
  436.         typealias TrimCompletion = (NSError?) -> ()
  437.         typealias TrimPoints = [(CMTime, CMTime)]
  438.        
  439.         let sourceURL = NSURL(fileURLWithPath: "/Users/marcocruz/Desktop/XCode/TV/ArgentinaChile.mp4")
  440.         let destinationURL = NSURL(fileURLWithPath: "/Users/marcocruz/Desktop/XCode 7/Server/Video\(milliseconds).mp4")
  441.        
  442.         let timeScale: Int32 = 1000
  443.        
  444.         var startTime = 0
  445.         let endTime = Int(milliseconds)
  446.        
  447.         if((endTime - 10000) >= 0){
  448.             startTime = endTime - 10000
  449.         }
  450.        
  451.         let trimPoints = [(CMTimeMake(Int64(startTime), timeScale), CMTimeMake(Int64(endTime), timeScale))]
  452.        
  453.         trimVideo(sourceURL, destinationURL: destinationURL, trimPoints: trimPoints) { error in
  454.             if let error = error {
  455.                 NSLog("Failure: \(error)")
  456.             } else {
  457.                 NSLog("Success")
  458.             }
  459.            
  460.         }
  461.  
  462.     }
  463. }
  464.  
  465. class PostResponse: RequestHandler {
  466.     func handleRequest(request: WebRequest, response: WebResponse) {
  467.        
  468.         let params = request.postParams
  469.         guard params.count == 4 else {
  470.             response.setStatus(400, message: "Wrong params!")
  471.             response.requestCompletedCallback(); return
  472.         }
  473.         let user_id : Int!
  474.         user_id = Int(request.param("userid")!)
  475.         let moment_id : Int!
  476.         moment_id = Int(request.param("momentid")!)
  477.         let opinion : String!
  478.         opinion = request.param("opinion")!
  479.         let emotion : String!
  480.         emotion = request.param("emotion")!
  481.        
  482.         let mysql = MySQL()
  483.         let connected = mysql.connect(HOST, user: USER, password: PASSWORD)
  484.        
  485.         guard connected else {
  486.             print(mysql.errorMessage())
  487.             response.setStatus(500, message: "Couldn't connect to database")
  488.             response.requestCompletedCallback(); return
  489.         }
  490.        
  491.         mysql.selectDatabase(DB_NAME)
  492.         let querySuccess = mysql.query("INSERT INTO Responses (moment_id, user_id, opinion, emotion) VALUES ('\(moment_id)', '\(user_id)', '\(opinion)', '\(emotion)');")
  493.        
  494.         guard querySuccess else {
  495.             print(mysql.errorMessage())
  496.             response.setStatus(500, message: "Something went wrong")
  497.             response.requestCompletedCallback(); return
  498.         }
  499.        
  500.         //pushNotificationsHandler.sendNotification()
  501.         print("New response: \(user_id), \(moment_id), \(opinion), \(emotion)");
  502.         response.setStatus(200, message: "response success")
  503.         response.requestCompletedCallback()
  504.     }
  505. }
  506.  
  507.  
  508.  
  509. class GetMatches: RequestHandler {
  510.     func handleRequest(request: WebRequest, response: WebResponse) {
  511.         let mysql = MySQL()
  512.         let connected = mysql.connect(HOST, user: USER, password: PASSWORD)
  513.        
  514.         guard connected else {
  515.             print(mysql.errorMessage())
  516.             response.setStatus(500, message: "Couldn't connect to MySQL")
  517.             response.requestCompletedCallback(); return
  518.         }
  519.        
  520.         mysql.selectDatabase(DB_NAME)
  521.         defer { mysql.close() }
  522.        
  523.         let querySuccess = mysql.query("SELECT match_id, home, visitor, home_score, visitor_score, status, (SELECT count(moment_id) FROM Moments WHERE match_id = m.match_id) AS moment_count, home_abbr, visitor_abbr FROM Matches m;")
  524.         guard querySuccess else {
  525.             print(mysql.errorMessage())
  526.             response.setStatus(500, message: "Things went wrong querying the table")
  527.             response.requestCompletedCallback(); return
  528.         }
  529.        
  530.         var results: MySQL.Results!
  531.         results = mysql.storeResults()
  532.        
  533.         guard results.numRows() != 0 else {
  534.             print("no matches were found")
  535.             response.setStatus(500, message: "No data.")
  536.             response.appendBodyString("Empty table.")
  537.             response.requestCompletedCallback(); return
  538.         }
  539.        
  540.         let result = resultsToJSON(results: results!, ["match_id", "home", "visitor", "home_score", "visitor_score", "status", "moment_count", "home_abbr", "visitor_abbr"])
  541.         guard result != nil else {
  542.             print("json encoding did not work very well... or at all")
  543.             response.setStatus(500, message: "no goo json encoding oops")
  544.             response.requestCompletedCallback(); return
  545.         }
  546.        
  547.         response.appendBodyString(result!)
  548.         response.setStatus(201, message: "Mission Success Here is all the matches")
  549.         response.requestCompletedCallback()
  550.     }
  551. }
  552.  
  553.  
  554.  
  555. class GetMoments: RequestHandler {
  556.     func handleRequest(request: WebRequest, response: WebResponse) {
  557.         let user_id : Int!
  558.         user_id = Int(request.param("userid")!)
  559.         let match_id : Int!
  560.         match_id = Int(request.param("matchid")!)
  561.        
  562.         let mysql = MySQL()
  563.         let connected = mysql.connect(HOST, user: USER, password: PASSWORD)
  564.        
  565.         guard connected else {
  566.             print(mysql.errorMessage())
  567.             response.setStatus(500, message: "Couldn't connect to MySQL")
  568.             response.requestCompletedCallback(); return
  569.         }
  570.        
  571.         mysql.selectDatabase(DB_NAME)
  572.         defer { mysql.close() }
  573.        
  574.         let querySuccess = mysql.query("SELECT moment_id, first_name, last_name, time, IF(EXISTS(SELECT 1 FROM Responses r WHERE r.moment_id = mo.moment_id AND r.user_id = '\(user_id)'),'yes', 'no')AS resp, (SELECT count(*) FROM Responses WHERE Responses.moment_id = mo.moment_id) AS reactions FROM Matches ma NATURAL JOIN Moments mo NATURAL JOIN Users u WHERE match_id = '\(match_id)' ORDER BY time DESC;")
  575.         guard querySuccess else {
  576.             print(mysql.errorMessage())
  577.             response.setStatus(500, message: "Things went wrong querying the table")
  578.             response.requestCompletedCallback(); return
  579.         }
  580.        
  581.         var results: MySQL.Results!
  582.         results = mysql.storeResults()
  583.        
  584.         guard results.numRows() != 0 else {
  585.             print("no moments were found")
  586.             response.setStatus(501, message: "No data.")
  587.             response.appendBodyString("Empty table.")
  588.             response.requestCompletedCallback(); return
  589.         }
  590.        
  591.         let result = resultsToJSON(results: results!, ["moment_id", "first_name", "last_name", "time", "resp", "reactions"])
  592.         guard result != nil else {
  593.             print("json encoding did not work very well... or at all")
  594.             response.setStatus(500, message: "no goo json encoding oops")
  595.             response.requestCompletedCallback(); return
  596.         }
  597.        
  598.         response.appendBodyString(result!)
  599.         response.setStatus(201, message: "Mission Success Here is all the moments")
  600.         response.requestCompletedCallback()
  601.     }
  602. }
  603.  
  604.  
  605. class GetResponses: RequestHandler {
  606.     func handleRequest(request: WebRequest, response: WebResponse) {
  607.         let moment_id : Int!
  608.         moment_id = Int(request.param("momentid")!)
  609.        
  610.         let mysql = MySQL()
  611.         let connected = mysql.connect(HOST, user: USER, password: PASSWORD)
  612.        
  613.         guard connected else {
  614.             print(mysql.errorMessage())
  615.             response.setStatus(500, message: "Couldn't connect to MySQL")
  616.             response.requestCompletedCallback(); return
  617.         }
  618.        
  619.         mysql.selectDatabase(DB_NAME)
  620.         defer { mysql.close() }
  621.        
  622.         let querySuccess = mysql.query("SELECT first_name, last_name, opinion, emotion FROM Responses NATURAL JOIN Users WHERE moment_id = \(moment_id);")
  623.         guard querySuccess else {
  624.             print(mysql.errorMessage())
  625.             response.setStatus(500, message: "Things went wrong querying the table")
  626.             response.requestCompletedCallback(); return
  627.         }
  628.        
  629.         var results: MySQL.Results!
  630.         results = mysql.storeResults()
  631.        
  632.         guard results.numRows() != 0 else {
  633.             print("no moments were found")
  634.             response.setStatus(500, message: "No data.")
  635.             response.appendBodyString("Empty table.")
  636.             response.requestCompletedCallback(); return
  637.         }
  638.        
  639.         let result = resultsToJSON(results: results!, ["first_name", "last_name", "opinion", "emotion"])
  640.         guard result != nil else {
  641.             print("json encoding did not work very well... or at all")
  642.             response.setStatus(500, message: "no goo json encoding oops")
  643.             response.requestCompletedCallback(); return
  644.         }
  645.        
  646.         response.appendBodyString(result!)
  647.         response.setStatus(201, message: "Mission Success Here is all the responses")
  648.         response.requestCompletedCallback()
  649.     }
  650. }
  651.  
  652.  
  653. class GetOpinions: RequestHandler {
  654.     func handleRequest(request: WebRequest, response: WebResponse) {
  655.         let moment_id : Int!
  656.         moment_id = Int(request.param("momentid")!)
  657.        
  658.         let mysql = MySQL()
  659.         let connected = mysql.connect(HOST, user: USER, password: PASSWORD)
  660.        
  661.         guard connected else {
  662.             print(mysql.errorMessage())
  663.             response.setStatus(500, message: "Couldn't connect to MySQL")
  664.             response.requestCompletedCallback(); return
  665.         }
  666.        
  667.         mysql.selectDatabase(DB_NAME)
  668.         defer { mysql.close() }
  669.        
  670.         let querySuccess = mysql.query("SELECT opinion, count(*) as number FROM Responses WHERE moment_id = \(moment_id) GROUP BY opinion;")
  671.         guard querySuccess else {
  672.             print(mysql.errorMessage())
  673.             response.setStatus(500, message: "Things went wrong querying the table")
  674.             response.requestCompletedCallback(); return
  675.         }
  676.        
  677.         var results: MySQL.Results!
  678.         results = mysql.storeResults()
  679.        
  680.         guard results.numRows() != 0 else {
  681.             print("no opinions were found")
  682.             response.setStatus(500, message: "No data.")
  683.             response.appendBodyString("Empty table.")
  684.             response.requestCompletedCallback(); return
  685.         }
  686.        
  687.         let result = resultsToJSON(results: results!, ["opinion", "number"])
  688.         guard result != nil else {
  689.             print("json encoding did not work very well... or at all")
  690.             response.setStatus(500, message: "no goo json encoding oops")
  691.             response.requestCompletedCallback(); return
  692.         }
  693.        
  694.         response.appendBodyString(result!)
  695.         response.setStatus(201, message: "Mission Success Here is all the opinions")
  696.         response.requestCompletedCallback()
  697.     }
  698. }
  699.  
  700. class GetEmotions: RequestHandler {
  701.     func handleRequest(request: WebRequest, response: WebResponse) {
  702.         let moment_id : Int!
  703.         moment_id = Int(request.param("momentid")!)
  704.        
  705.         let mysql = MySQL()
  706.         let connected = mysql.connect(HOST, user: USER, password: PASSWORD)
  707.        
  708.         guard connected else {
  709.             print(mysql.errorMessage())
  710.             response.setStatus(500, message: "Couldn't connect to MySQL")
  711.             response.requestCompletedCallback(); return
  712.         }
  713.        
  714.         mysql.selectDatabase(DB_NAME)
  715.         defer { mysql.close() }
  716.        
  717.         let querySuccess = mysql.query("SELECT emotion, count(*) as number FROM Responses WHERE moment_id = \(moment_id) GROUP BY emotion;")
  718.         guard querySuccess else {
  719.             print(mysql.errorMessage())
  720.             response.setStatus(500, message: "Things went wrong querying the table")
  721.             response.requestCompletedCallback(); return
  722.         }
  723.        
  724.         var results: MySQL.Results!
  725.         results = mysql.storeResults()
  726.        
  727.         guard results.numRows() != 0 else {
  728.             print("no emotions were found")
  729.             response.setStatus(500, message: "No data.")
  730.             response.appendBodyString("Empty table.")
  731.             response.requestCompletedCallback(); return
  732.         }
  733.        
  734.         let result = resultsToJSON(results: results!, ["emotion", "number"])
  735.         guard result != nil else {
  736.             print("json encoding did not work very well... or at all")
  737.             response.setStatus(500, message: "no goo json encoding oops")
  738.             response.requestCompletedCallback(); return
  739.         }
  740.        
  741.         response.appendBodyString(result!)
  742.         response.setStatus(201, message: "Mission Success Here is all the emotions")
  743.         response.requestCompletedCallback()
  744.     }
  745. }
  746.  
  747.  
  748.  
  749.  
  750. class GetFriendsReactions: RequestHandler {
  751.     func handleRequest(request: WebRequest, response: WebResponse) {
  752.         let moment_id : Int!
  753.         moment_id = Int(request.param("momentid")!)
  754.        
  755.         let mysql = MySQL()
  756.         let connected = mysql.connect(HOST, user: USER, password: PASSWORD)
  757.        
  758.         guard connected else {
  759.             print(mysql.errorMessage())
  760.             response.setStatus(500, message: "Couldn't connect to MySQL")
  761.             response.requestCompletedCallback(); return
  762.         }
  763.        
  764.         mysql.selectDatabase(DB_NAME)
  765.         defer { mysql.close() }
  766.        
  767.         let querySuccess = mysql.query("SELECT first_name, last_name, opinion, emotion FROM Responses NATURAL JOIN Users WHERE moment_id = \(moment_id);")
  768.         guard querySuccess else {
  769.             print(mysql.errorMessage())
  770.             response.setStatus(500, message: "Things went wrong querying the table")
  771.             response.requestCompletedCallback(); return
  772.         }
  773.        
  774.         var results: MySQL.Results!
  775.         results = mysql.storeResults()
  776.        
  777.         guard results.numRows() != 0 else {
  778.             print("no friends were found")
  779.             response.setStatus(500, message: "No data.")
  780.             response.appendBodyString("Empty table.")
  781.             response.requestCompletedCallback(); return
  782.         }
  783.        
  784.         let result = resultsToJSON(results: results!, ["first_name", "last_name", "opinion", "emotion"])
  785.         guard result != nil else {
  786.             print("json encoding did not work very well... or at all")
  787.             response.setStatus(500, message: "no goo json encoding oops")
  788.             response.requestCompletedCallback(); return
  789.         }
  790.        
  791.         response.appendBodyString(result!)
  792.         response.setStatus(201, message: "Mission Success Here are all the friends reactions")
  793.         response.requestCompletedCallback()
  794.     }
  795. }
  796.  
  797.  
  798.  
  799.  
  800. extension NSTimeInterval {
  801.     var minuteSecondMS: String {
  802.         return String(format:"%d:%02d", minute, second)
  803.     }
  804.     var minute: Int {
  805.         return Int(self/60.0 % 60)
  806.     }
  807.     var second: Int {
  808.         return Int(self % 60)
  809.     }
  810. }
  811.  
  812. extension Int {
  813.     var msToSeconds: Double {
  814.         return Double(self) / 1000
  815.     }
  816. }
  817.  
  818. private func getMiliseconds(date: NSDate) -> Int
  819. {
  820.     let calendar = NSCalendar.currentCalendar()
  821.     let components = calendar.components([ .Hour, .Minute, .Second], fromDate: date)
  822.     let hour = components.hour
  823.     let minutes = components.minute
  824.     let seconds = components.second
  825.    
  826.     return (((3600*hour) + (60*minutes) + seconds) * 1000)
  827. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top