MessageSplitViewController.swift 6.65 KB
Newer Older
1
2
3
4
5
6
7
8
9
//
//  MessageSplitViewController.swift
//  MessageTextEntrySpike
//
//  Created by Aral Balkan on 03/01/2015.
//  Copyright (c) 2015 ind.ie. All rights reserved.
//

import Cocoa
10
11
import Foundation

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public struct Message
{
    public var id:String
    public var folderURL:NSURL
    public var html:String
    public var synced:Bool = false
    
    func JSONString() -> String
    {
        let dict = ["id": self.id, "folderURL": self.folderURL.absoluteString!, "html": self.html, "synced":self.synced]
        let jsonString = JSON(dict).rawString()
        
        if let jsonString = jsonString
        {
            return jsonString
        }
        else
        {
            return ""
        }
    }
}
34

35
36
class MessageSplitViewController: NSSplitViewController
{
37

38
39
40
    var iso8601DateFormatter:ISO8601DateFormatter!

    
41
42
43
    override func viewDidLoad()
    {
        super.viewDidLoad()
44
45
46
47
48
49
50
51
        
        // Set up the ISO 8601 date formatter.
        iso8601DateFormatter = ISO8601DateFormatter()
        iso8601DateFormatter.format = .Calendar
        iso8601DateFormatter.includeTime = true
        iso8601DateFormatter.useMillisecondPrecision = true
        iso8601DateFormatter.timeSeparator = ("_" as NSString).characterAtIndex(0)
        
52
53
54
55
56
57
58
59
60
        NSNotificationCenter.defaultCenter().when(youGet: MessageNotification.named(.SendMessage), call: "sendMessage:", on: self)
    }
    
    
    func sendMessage(notification:NSNotification)
    {
        let timelineViewController = (self.splitViewItems[0] as! NSSplitViewItem).viewController as! TimelineViewController
        if let userInfo = (notification.userInfo as Dictionary!)
        {
61
62
            let messageAttributedString = userInfo["message"] as! NSAttributedString
            println("Send message: received text: \(messageAttributedString)")
63
            
64
65
66
67
68
69
70
71
72
73
74
75
76
            //
            // Get the folder to save the message to based on the current timeline
            //
            
            let _currentTimelinePath = timelineViewController.currentTimelinePath()
            
            if _currentTimelinePath == nil
            {
                fatalError("Conversation messages not implemented yet. Panicing!")
            }
            
            let currentTimelinePath = _currentTimelinePath!
            
77
78
79
            //
            // Create a file wrapper to save the contents as a directory.
            //
80
            let messageDirectoryWrapper:NSFileWrapper? = messageAttributedString.fileWrapperFromRange(NSMakeRange(0, messageAttributedString.length), documentAttributes: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding, NSExcludedElementsDocumentAttribute: ["xml", "html", "head", "body", "font", "span"], NSPrefixSpacesDocumentAttribute: 4], error: nil)
81
            
82
83
84
85
86
87
88
89
            // The file name of the message folder (this is the unique ID — unique per message folder) is the current timestamp in ISO 8601 format
            let messageFileName = iso8601DateFormatter.stringFromDate(NSDate(), timeZone: NSTimeZone(abbreviation: "UTC"))
            
            let filePath = NSHomeDirectory().stringByAppendingPathComponent("Pulse/Sync").stringByAppendingPathComponent(currentTimelinePath).stringByAppendingPathComponent(messageFileName)
            
            println("About to save message at path: \(filePath)")
            
            let fileURL:NSURL? = NSURL(fileURLWithPath: filePath, isDirectory: true)
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
            
            if let messageDirectoryWrapper = messageDirectoryWrapper, fileURL = fileURL
            {
                let messageFileWrappers:[NSObject:AnyObject] = messageDirectoryWrapper.fileWrappers
                
                for (fileName, fileWrapper) in messageFileWrappers
                {
                    println(" * \(fileName): \(fileWrapper)")
                    if fileName == "index.html"
                    {
                        let indexData:NSData? = fileWrapper.regularFileContents
                        if let indexData = indexData
                        {
                            let indexHTML = NSString(data: indexData, encoding: NSUTF8StringEncoding)
                            if var indexHTML = indexHTML
                            {
                                //
                                // Massage the HTML.
                                //
                                
                                // Fix image URLs
                                indexHTML = indexHTML.stringByReplacingOccurrencesOfString("file:///", withString: "")
                                
                                // Remove redundant empty lines.
                                indexHTML = indexHTML.stringByReplacingOccurrencesOfString("<p><br></p>", withString: "")
                                
                                //
                                // Update the index.html.
                                //
                                
                                // Remove the index.html file wrapper.
                                messageDirectoryWrapper.removeFileWrapper(fileWrapper as! NSFileWrapper)
                                
                                // And replace it with the new index.html we created.
                                let newIndexHTMLData:NSData? = indexHTML.dataUsingEncoding(NSUTF8StringEncoding)
                                
                                if let newIndexHTMLData = newIndexHTMLData
                                {
                                    let newIndexHTMLFileWrapper = NSFileWrapper(regularFileWithContents: newIndexHTMLData)
                                    newIndexHTMLFileWrapper.preferredFilename = "index.html"
                                    messageDirectoryWrapper.addFileWrapper(newIndexHTMLFileWrapper)
                                }
132
133
134
135
136
137
138
139
140
141
142
143
                                
                                // TODO: Error checking.
                                messageDirectoryWrapper.writeToURL(fileURL, options: NSFileWrapperWritingOptions.Atomic, originalContentsURL: nil, error: nil)
                                println(messageDirectoryWrapper)

                                //
                                // Create the message object and show it in the timeline.
                                //
                                let message = Message(id: messageFileName, folderURL: fileURL, html: indexHTML as String, synced: false)
                                timelineViewController.showMessage(message)
                                
                                break
144
145
146
147
148
149
150
151
                            }
                        }
                    }
                }
            }
        }
    }
}