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

import Cocoa
12

13
14
class MessageSplitViewController: NSSplitViewController
{
15

16
17
    var iso8601DateFormatter:ISO8601DateFormatter!

18
    var sendMessageNotificationHandler:NotificationHandler?
19
    
20
21
22
23
24
    //
    // MARK: - View lifecycle
    //
    
    
25
26
27
    override func viewDidLoad()
    {
        super.viewDidLoad()
28
29
30
31
32
33
34
35
        
        // Set up the ISO 8601 date formatter.
        iso8601DateFormatter = ISO8601DateFormatter()
        iso8601DateFormatter.format = .Calendar
        iso8601DateFormatter.includeTime = true
        iso8601DateFormatter.useMillisecondPrecision = true
        iso8601DateFormatter.timeSeparator = ("_" as NSString).characterAtIndex(0)
        
36
37
38
    }
    
    
39
40
41
    override func viewWillAppear()
    {
        createConstraints()
42
43
        
        addNotificationHandlers()
44
45
46
    }
    
    
47
    override func viewWillDisappear()
48
    {
49
        removeNotificationHandlers()
50
51
52
    }
    
    //
53
    // MARK: - Notification handlers
54
55
    //
    
56
    func addNotificationHandlers()
57
    {
58
        sendMessageNotificationHandler = handle(MessageNotification.named(.SendMessage))
59
        {
60
            /* as */ notification in
61
            
62
63
            let timelineViewController = (self.splitViewItems[0] as! NSSplitViewItem).viewController as! TimelineViewController
            if let userInfo = (notification.userInfo as Dictionary!)
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
                let messageAttributedString = userInfo["message"] as! NSAttributedString
                println("Send message: received text: \(messageAttributedString)")
                
                //
                // 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!
                
                println("Current timeline path = \(currentTimelinePath)")
                
                //
                // Get the correct web prefix
                //
                let _currentTimelineRelativeWebPrefix = timelineViewController.currentTimelineRelativeWebPrefix()
                
                if _currentTimelineRelativeWebPrefix == nil
                {
                    fatalError("Could not get relative web prefix for current timeline — not implemented. Only Private, All Friends, and Public timlines implemented at the moment.")
                }
                
                let currentTimelineRelativeWebPrefix = _currentTimelineRelativeWebPrefix!
                
                println("Current timeline relative web prefix: \(currentTimelineRelativeWebPrefix)")
                
                //
                // Create a file wrapper to save the contents as a directory.
                //
                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)
                
                // 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 = self.iso8601DateFormatter.stringFromDate(NSDate(), timeZone: NSTimeZone(abbreviation: "UTC"))
                
                // This is the URL that will be prefixed to all assets in the HTML (images, etc.)
                let assetURLPrefix = currentTimelineRelativeWebPrefix.stringByAppendingPathComponent(messageFileName)
                
                println("Message file name: \(messageFileName)")
                
                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)
115
                
116
                if let messageDirectoryWrapper = messageDirectoryWrapper, fileURL = fileURL
117
                {
118
119
120
                    let messageFileWrappers:[NSObject:AnyObject] = messageDirectoryWrapper.fileWrappers
                    
                    for (fileName, fileWrapper) in messageFileWrappers
121
                    {
122
123
                        println(" * \(fileName): \(fileWrapper)")
                        if fileName == "index.html"
124
                        {
125
126
                            let indexData:NSData? = fileWrapper.regularFileContents
                            if let indexData = indexData
127
                            {
128
129
                                let indexHTML = NSString(data: indexData, encoding: NSUTF8StringEncoding)
                                if var indexHTML = indexHTML
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
                                    //
                                    // Massage the HTML.
                                    //
                                    
                                    // Fix image URLs
                                    indexHTML = indexHTML.stringByReplacingOccurrencesOfString("file:///", withString: assetURLPrefix.stringByAppendingString("/"))
                                    
                                    // 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)
                                    }
                                    
                                    // TODO: Error checking.
                                    messageDirectoryWrapper.writeToURL(fileURL, options: NSFileWrapperWritingOptions.Atomic, originalContentsURL: nil, error: nil)
                                    println(messageDirectoryWrapper)
                                    
                                    //
163
                                    // Create the message object and broadcast it.
164
165
                                    //
                                    let message = Message(id: messageFileName, assetURLPrefix: assetURLPrefix, folderURL: fileURL, html: indexHTML as String, synced: false)
166
167
                            
                                    post(MessageNotification.named(.ShowMessage), from: self, with: ["message": message])
168
169
                                    
                                    break
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
    
    
    func removeNotificationHandlers()
    {
        sendMessageNotificationHandler?.remove()
    }
    
    
    //
    // MARK: - Layout
    //
    
    func createConstraints()
    {
        view.removeConstraints(view.constraints)
        
        layout(view)
        {
            /* as */ view in
            
            view.width == view.superview!.width
            view.height == view.superview!.height
        }
    }
    
203
}