forked from conceptdev/iSOFlair
/
SOViewController.xib.cs
341 lines (308 loc) · 11.1 KB
/
SOViewController.xib.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
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
163
164
165
166
167
168
169
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Net;
using System.Text;
namespace iSOFlair
{
/// <summary>
/// Flair page 'template', re-used four times
/// </summary>
public partial class SOViewController : UIViewController
{
#region Constructors
// The IntPtr and NSCoder constructors are required for controllers that need
// to be able to be created from a xib rather than from managed code
public SOViewController (IntPtr handle) : base(handle)
{
Initialize ();
}
[Export("initWithCoder:")]
public SOViewController (NSCoder coder) : base(coder)
{
Initialize ();
}
public SOViewController ()
{
Initialize ();
}
void Initialize ()
{
}
#endregion
private TrilogySite _site = null;
public TrilogySite Site {
get { return _site; }
set {
_site = value;
imageLogo.Image = UIImage.FromFile (Site.Logo);
}
}
/// <summary>
/// Path to save image and cache
/// </summary>
public string DocumentsDirectory { get; set; }
public string Username {
get { return labelUsername.Text; }
set { labelUsername.Text = value; }
}
public string Points {
get { return labelPoints.Text; }
set { labelPoints.Text = value; }
}
private string ImagePath {
get { return Path.Combine (DocumentsDirectory, Site.PreferencesPrefix + "gravatar.png"); }
}
private string CachePath {
get { return Path.Combine (DocumentsDirectory, Site.PreferencesPrefix + "cache.txt"); }
}
/// <summary>
/// Setup the button delegates
/// </summary>
public void WireUp ()
{
buttonUpdate.TouchDown += delegate {
buttonUpdate.Hidden = true;
buttonSafari.Hidden = true;
ScreenCapture ();
buttonUpdate.Hidden = false;
buttonSafari.Hidden = false;
};
buttonSafari.TouchDown += delegate { UIApplication.SharedApplication.OpenUrl (new NSUrl (String.Format (Site.ProfileUrl, Site.SiteId))); };
}
#region respond to shaking (OS3+)
// also requires you to put
// UIApplication.SharedApplication.ApplicationSupportsShakeToEdit = true;
// in Main.cs : FinishedLaunching()
public override bool CanBecomeFirstResponder {
get { return true; }
}
public override void ViewDidAppear (bool animated)
{
base.ViewDidAppear (animated);
this.BecomeFirstResponder ();
}
public override void ViewWillDisappear (bool animated)
{
this.ResignFirstResponder ();
base.ViewWillDisappear (animated);
}
public override void MotionEnded (UIEventSubtype motion, UIEvent evt)
{
Console.WriteLine ("Motion detected");
if (motion == UIEventSubtype.MotionShake) {
Console.WriteLine ("and was a shake");
labelLastUpdated.Text = "All shook up! Updating...";
// never appears
// Do your application-specific shake response here...
Update ();
}
}
#endregion
/// <summary>
/// Load data from txt file (cached from last webclient request)
/// </summary>
public bool LoadFromCache ()
{
bool loaded = false;
Console.WriteLine ("Loading from cache.txt");
try {
string cache = "";
if (File.Exists (CachePath)) {
cache = System.IO.File.ReadAllText (CachePath);
}
if (cache == "") {
labelConnectionError.Text = "Cache is empty. Shake to refresh data.";
labelUsername.Text = "";
labelPoints.Text = "";
labelGoldBadges.Text = "";
labelSilverBadges.Text = "";
labelBronzeBadges.Text = "";
textDebug.Text = "";
} else {
string[] cacheItems = cache.Split ('?');
labelUsername.Text = cacheItems[0];
labelPoints.Text = cacheItems[1];
labelGoldBadges.Text = cacheItems[2] + " gold badges";
labelSilverBadges.Text = cacheItems[3] + " silver badges";
labelBronzeBadges.Text = cacheItems[4] + " bronze badges";
//profileUrl = cacheItems[5];
labelLastUpdated.Text = cacheItems[6] + " from cache";
textDebug.Text = "";
// blank out, nothing loaded from the web
if (File.Exists (ImagePath)) {
UIImage img = UIImage.FromFileUncached (ImagePath);
// TODO: WHY didn't FromFile work, when FromFileUncached does?
if (img != null)
this.imageAvatar.Image = img;
}
loaded = true;
}
} catch (Exception ex) {
labelConnectionError.Text = "Cache is invalid. Shake to refresh data.";
labelUsername.Text = "";
labelPoints.Text = "";
labelGoldBadges.Text = "";
labelSilverBadges.Text = "";
labelBronzeBadges.Text = "";
textDebug.Text = "";
}
return loaded;
}
/// <summary>
/// Update this site data from the web, but downloading the flair, parsing
/// and saving in a cache text file
/// </summary>
public void Update ()
{
Console.WriteLine ("Loading from web " + Site.SiteId);
labelLastUpdated.Text = "Loading...";
// Download flair page
WebClient wc = new WebClient ();
Uri uri = new Uri (String.Format (Site.FlairUrl, Site.SiteId));
byte[] bytes = null;
try {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
bytes = wc.DownloadData (uri);
} catch (Exception ex) {
Console.WriteLine ("Internet connection failed: " + ex.Message);
textDebug.Text = Environment.NewLine + "DOWNLOADDATA:" + Environment.NewLine + ex.Message;
labelLastUpdated.Text = "Internet connection failed: " + ex.Message;
labelConnectionError.Text = "Update failed: cannot connect to the Internet.";
return;
} finally {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
}
// Parse flair HTML
try {
string result = Encoding.UTF8.GetString (bytes);
int startpos = result.IndexOf ("<a");
startpos = result.IndexOf ("href=", startpos) + 6;
int endpos = result.IndexOf ("\"", startpos);
string profileUrl = result.Substring (startpos, endpos - startpos);
startpos = result.IndexOf ("img src", endpos) + 9;
endpos = result.IndexOf ("\"", startpos);
// download image
string gravatarUrl = result.Substring (startpos, endpos - startpos);
uri = new Uri (gravatarUrl);
try {
Console.WriteLine ("wc.Download(" + uri + "," + ImagePath + ")");
wc.DownloadFile (uri, ImagePath);
} catch (Exception ex1) {
textDebug.Text += Environment.NewLine + "DOWNLOAD IMAGE:" + Environment.NewLine + gravatarUrl + Environment.NewLine + ImagePath + Environment.NewLine + ex1.Message;
}
// Parse the HTML
//HACK: yes this is a hack... HtmlAgilityPack would've been smarter.
startpos = result.IndexOf ("username", endpos);
startpos = result.IndexOf ("_blank", endpos) + 8;
endpos = result.IndexOf ("<", startpos);
string username = result.Substring (startpos, endpos - startpos);
labelUsername.Text = username;
startpos = result.IndexOf ("reputation score", endpos) + 18;
endpos = result.IndexOf ("<", startpos);
string points = result.Substring (startpos, endpos - startpos);
string goldBadges = "", silverBadges = "", bronzeBadges = "";
startpos = result.IndexOf ("gold badge", endpos);
if (startpos > 0) {
startpos--;
// remove preceding space
endpos = result.IndexOf ("\"", startpos - 10) + 1;
goldBadges = result.Substring (endpos, startpos - endpos);
Console.WriteLine (" " + goldBadges);
labelGoldBadges.Text = goldBadges + " gold badges";
}
startpos = result.IndexOf ("silver badge", endpos);
if (startpos > 0) {
startpos--;
// remove preceding space
endpos = result.IndexOf ("\"", startpos - 10) + 1;
silverBadges = result.Substring (endpos, startpos - endpos);
labelSilverBadges.Text = silverBadges + " silver badges";
}
startpos = result.IndexOf ("bronze badge", endpos);
if (startpos > 0) {
startpos--;
// remove preceding space
endpos = result.IndexOf ("\"", startpos - 10) + 1;
bronzeBadges = result.Substring (endpos, startpos - endpos);
labelBronzeBadges.Text = bronzeBadges + " bronze badges";
}
// load image from file into UIImage
try {
if (File.Exists (ImagePath)) {
//UIImage img = UIImage.FromFile (ImagePath); // WHY does this break???
UIImage img = UIImage.FromFileUncached (ImagePath);
// BUT this works???
if (img != null)
this.imageAvatar.Image = img;
} else {
textDebug.Text += Environment.NewLine + "UIIMAGE NOT EXIST:" + Environment.NewLine + ImagePath;
}
} catch (Exception ex2) {
textDebug.Text += Environment.NewLine + "FROM FILE: " + Environment.NewLine + ImagePath + Environment.NewLine + ex2.Message;
}
Console.WriteLine ("gold " + goldBadges);
Console.WriteLine ("silver " + silverBadges);
Console.WriteLine ("bronze " + bronzeBadges);
labelPoints.Text = points;
string dateUpdated = "Last updated " + DateTime.Now.ToString ("dd-MMM-yy hh:mm:ss");
labelLastUpdated.Text = dateUpdated;
string cache = String.Format ("{0}?{1}?{2}?{3}?{4}?{5}?{6}", username, points, goldBadges, silverBadges, bronzeBadges, profileUrl, dateUpdated);
System.IO.File.WriteAllText (CachePath, cache);
labelConnectionError.Text = "";
// blank out if we get to here without Exception
} catch (Exception ex) {
labelLastUpdated.Text = ex.Message;
textDebug.Text += Environment.NewLine + ex.Message;
}
}
/// <summary>
/// Capture a copy of the current View and:
/// * re-display in a UIImage control
/// * save to the Photos collection
/// * save to disk in the application's Documents folder
/// </summary>
public void ScreenCapture ()
{
Console.WriteLine ("start image cap");
Console.WriteLine ("frame" + this.View.Frame.Size);
UIGraphics.BeginImageContext (View.Frame.Size);
var documentsDirectory = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
var ctx = UIGraphics.GetCurrentContext ();
if (ctx != null) {
Console.WriteLine ("ctx not null");
View.Layer.RenderInContext (ctx);
Console.WriteLine ("render in context");
UIImage img = UIGraphics.GetImageFromCurrentImageContext ();
Console.WriteLine ("get from current content");
UIGraphics.EndImageContext ();
// Set to display in a UIImage control _on_ the view
//imageLogo.Image = img;
// Save to Photos
img.SaveToPhotosAlbum ((sender, args) =>
{
Console.WriteLine ("image saved to Photos");
var av = new UIAlertView ("Screenshot saved", "Image saved to " + Environment.NewLine + "Photos : Camera Roll", null, "Ok thanks", null);
av.Show ();
});
// thought this "might" overwrite the splashscreen
//string png = Path.Combine (documentsDirectory, "../iSOFlair.app/Default.png");
// Save to application's Documents folder, kinda pointless except as an example
// since there is no way to "read" it
string png = Path.Combine (documentsDirectory, "Screenshot.png");
NSData imgData = img.AsPNG ();
NSError err = null;
if (imgData.Save (png, false, out err)) {
Console.WriteLine ("saved " + png);
} else {
Console.WriteLine ("not saved" + png + " because" + err.LocalizedDescription);
}
} else {
Console.WriteLine ("ctx null - doesn't happen but wasn't sure at first");
}
}
}
}