Add an update check and see if the current version is the most recent one
[printdrop.git] / Source / AppController.m
1 /*
2 * PrintDrop
3 * Copyright (c) 2008, Blue Static <http://www.bluestatic.org>
4 *
5 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
6 * General Public License as published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
10 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along with this program; if not,
14 * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
15 */
16
17 #import "AppController.h"
18 #import <libssh2.h>
19 #import <sys/socket.h>
20 #import <arpa/inet.h>
21 #include <netdb.h>
22
23 @interface AppController (Private)
24
25 - (void)setStatus:(NSString *)msg isError:(BOOL)error;
26
27 - (void)readChannel:(LIBSSH2_CHANNEL *)channel;
28 - (void)uploadAndPrint:(id)sender;
29
30 @end
31
32
33 @implementation AppController
34
35 /**
36 * Set up the printer list
37 */
38 - (id)init
39 {
40 if (self = [super init])
41 {
42 printers = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Printers" ofType:@"plist"]];
43 [NSThread detachNewThreadSelector:@selector(versionCheck:) toTarget:self withObject:self];
44 }
45 return self;
46 }
47
48 /**
49 * Checks and sees if the current version is the most up-to-date one
50 */
51 - (void)versionCheck:(id)sender
52 {
53 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
54
55 NSMutableString *version = [NSMutableString stringWithString:[[[NSBundle mainBundle] infoDictionary] valueForKey:@"CFBundleShortVersionString"]];
56 version = [NSMutableString stringWithString:@"1.0 Beta 1"];
57 [version replaceOccurrencesOfString:@" " withString:@"-" options:NSLiteralSearch range:NSMakeRange(0, [version length])];
58
59 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.bluestatic.org/versioncheck.php?prod=printdrop&ver=%@", version]];
60 NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
61 NSURLResponse *response;
62 NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
63
64 if (result == nil)
65 {
66 goto end;
67 }
68
69 NSXMLDocument *xml = [[NSXMLDocument alloc] initWithData:result options:0 error:nil];
70 NSXMLNode *comp = [[xml rootElement] childAtIndex:0];
71 if ([[comp name] isEqualToString:@"update"])
72 {
73 [updateString setStringValue:[NSString stringWithFormat:[updateString stringValue], [comp stringValue]]];
74 [updateWindow makeKeyAndOrderFront:self];
75 }
76
77 end:
78 [pool release];
79 }
80
81
82 /**
83 * Opens the URL to the download page
84 */
85 - (IBAction)openUpdateInformation:(id)sender
86 {
87 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.bluestatic.org/software/printdrop/"]];
88 }
89
90 /**
91 * Sets the status text
92 */
93 - (void)setStatus:(NSString *)msg isError:(BOOL)error
94 {
95 [status setStringValue:msg];
96 if (error)
97 {
98 [status setTextColor:[NSColor redColor]];
99 [progress stopAnimation:self];
100 }
101 else
102 {
103 [status setTextColor:[NSColor blackColor]];
104 }
105 }
106
107 /**
108 * Reads through a channel (in non-blocking) mode until there is no more left to read
109 * and then it returns. This calls sleep(1) so that the channel can have time to process.
110 * Be sure this is threaded otherwis the interface will stall.
111 */
112 - (void)readChannel:(LIBSSH2_CHANNEL *)channel
113 {
114 libssh2_channel_set_blocking(channel, 0);
115
116 char buf[1024];
117 int numbytes;
118 do
119 {
120 memset(&buf, '\0', sizeof(buf));
121 numbytes = libssh2_channel_read(channel, buf, sizeof(buf));
122 sleep(1);
123 #ifdef BLU_DEBUG
124 NSLog(@"buf: %s", buf);
125 #endif
126 } while (libssh2_poll_channel_read(channel, 0));
127 }
128
129 /**
130 * Sends an item to the printer
131 */
132 - (IBAction)print:(id)sender
133 {
134 [NSThread detachNewThreadSelector:@selector(uploadAndPrint:) toTarget:self withObject:sender];
135 }
136
137 /**
138 * Opens an SSH session, creates a SCP channel to upload the file, followed by a shell channel
139 * to queue up LPR
140 */
141 - (void)uploadAndPrint:(id)sender
142 {
143 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
144
145 [progress startAnimation:self];
146 [progress setHidden:NO];
147 [status setHidden:NO];
148
149 FILE *localFile;
150 struct stat fileInfo;
151
152 [self setStatus:@"Connecting to acs.bu.edu" isError:NO];
153 struct sockaddr_in sin;
154 int sock = socket(AF_INET, SOCK_STREAM, 0);
155 sin.sin_port = htons(22);
156 sin.sin_family = AF_INET;
157
158 struct hostent *host = gethostbyname("acs.bu.edu");
159 memcpy(&sin.sin_addr, host->h_addr_list[0], host->h_length);
160
161 if (stat([[dragRegion filePath] UTF8String], &fileInfo))
162 {
163 return [self setStatus:@"Invalid file selected" isError:YES];
164 }
165
166 if (connect(sock, (struct sockaddr *)(&sin), sizeof(struct sockaddr_in)) != 0)
167 {
168 return [self setStatus:@"Could not connect to acs.bu.edu" isError:YES];
169 }
170
171 LIBSSH2_SESSION *ssh = libssh2_session_init();
172 if (ssh == NULL)
173 {
174 return [self setStatus:@"Failed to initialize SSH context" isError:YES];
175 }
176
177 if (libssh2_session_startup(ssh, sock))
178 {
179 return [self setStatus:@"Could not tunnel over SSH" isError:YES];
180 }
181
182 if (libssh2_userauth_password(ssh, [[username stringValue] UTF8String], [[password stringValue] UTF8String]))
183 {
184 [self setStatus:@"Bad username/password" isError:YES];
185 goto shutdown;
186 }
187
188 LIBSSH2_CHANNEL *channel = libssh2_scp_send(ssh, "~/__bu_print_drop__.pdf", 0755, (unsigned long)fileInfo.st_size);
189 if (!channel)
190 {
191 [self setStatus:@"Unable to open upload SCP session" isError:YES];
192 goto shutdown;
193 }
194
195 [self setStatus:@"Uploading file..." isError:NO];
196
197 localFile = fopen([[dragRegion filePath] UTF8String], "r");
198 char buf[1024];
199 char *pbuf;
200 int numread, numwrote;
201 do
202 {
203 numread = fread(buf, 1, sizeof(buf), localFile);
204 if (numread <= 0)
205 {
206 break;
207 }
208
209 pbuf = buf;
210 do
211 {
212 numwrote = libssh2_channel_write(channel, pbuf, numread);
213 pbuf += numwrote;
214 numread -= numread;
215 } while (numwrote > 0);
216
217 } while(1);
218
219 [self setStatus:@"File uploaded!" isError:NO];
220
221 libssh2_channel_send_eof(channel);
222 libssh2_channel_wait_eof(channel);
223 libssh2_channel_wait_closed(channel);
224 libssh2_channel_free(channel);
225 channel = NULL;
226
227 channel = libssh2_channel_open_session(ssh);
228 if (!channel)
229 {
230 [self setStatus:@"Could not open SSH channel for printing" isError:YES];
231 goto shutdown;
232 }
233
234 if (libssh2_channel_request_pty(channel, "vanilla"))
235 {
236 [self setStatus:@"Could not open ANSI TTY" isError:YES];
237 goto shutdown;
238 }
239
240 if (libssh2_channel_shell(channel))
241 {
242 [self setStatus:@"Failed to open remote shell" isError:YES];
243 goto shutdown;
244 }
245
246 [self setStatus:@"Opened remote SSH shell" isError:NO];
247
248 // read the banner
249 [self readChannel:channel];
250
251 // send the job to lpr
252 char *cmd;
253 #ifndef BLU_DEBUG
254 NSString *printer = [[printersController selection] valueForKey:@"unixName"];
255 cmd = (char *)[[NSString stringWithFormat:@"lpr -m -P%@ __bu_print_drop__.pdf\r\n\0", printer] UTF8String];
256 #else
257 cmd = "touch abc.def\r\n\0";
258 #endif
259 libssh2_channel_write(channel, cmd, sizeof(char) * strlen(cmd));
260 [self readChannel:channel];
261
262 // remove our temp file
263 cmd = "rm -f __bu_print_drop__.pdf\r\n\0";
264 libssh2_channel_write(channel, cmd, sizeof(char) * strlen(cmd));
265 [self readChannel:channel];
266
267 [self setStatus:@"Printed!" isError:NO];
268
269 libssh2_channel_send_eof(channel);
270 libssh2_channel_eof(channel);
271 libssh2_channel_close(channel);
272
273 shutdown:
274 if (channel)
275 {
276 //libssh2_channel_free(channel);
277 channel = NULL;
278 }
279 libssh2_session_disconnect(ssh, "Normal disconnect.");
280 libssh2_session_free(ssh);
281
282 close(sock);
283
284 [progress stopAnimation:self];
285
286 [pool release];
287 }
288
289 @end