Menu

[r677]: / trunk / GoogleContactsSync / Utilities.cs  Maximize  Restore  History

Download this file

689 lines (600 with data), 23.4 kB

  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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Net;
using System.IO;
using Google.GData.Contacts;
using Outlook = Microsoft.Office.Interop.Outlook;
using System.Threading;
using System.Collections.ObjectModel;
using Google.Contacts;
namespace GoContactSyncMod
{
internal static class Utilities
{
//private static string tempPhotoPath = AppDomain.CurrentDomain.BaseDirectory + "\\TempOutlookContactPhoto.jpg";
//private static string tempPhotoPath = Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + @"\" + System.Windows.Forms.Application.ProductName + @"\TempOutlookContactPhoto.jpg";
private static string tempPhotoPath = Path.GetTempPath() + @"\TempOutlookContactPhoto.jpg";
public static byte[] BitmapToBytes(Bitmap bitmap)
{
//bitmap
using (MemoryStream stream = new MemoryStream())
{
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
return stream.ToArray();
}
}
public static bool HasPhoto(Contact googleContact)
{
if (googleContact.PhotoEtag == null)
return false;
return true;
}
public static bool HasPhoto(Outlook.ContactItem outlookContact)
{
return outlookContact.HasPicture;
}
public static bool SaveGooglePhoto(Synchronizer sync, Contact googleContact, Image image)
{
if (googleContact.ContactEntry.PhotoUri == null)
throw new Exception("Must reload contact from google.");
try
{
using (var client = new WebClient())
{
//client.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + sync.ContactsRequest.Service.QueryClientLoginToken());
client.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + sync.ContactsRequest.Settings.OAuth2Parameters.AccessToken);
client.Headers.Add(HttpRequestHeader.ContentType, "image/*");
using (var pic = new Bitmap(image))
{
using (var s = client.OpenWrite(googleContact.ContactEntry.PhotoUri.AbsoluteUri, "PUT"))
{
byte[] bytes = BitmapToBytes(pic);
s.Write(bytes, 0, bytes.Length);
s.Flush();
}
}
}
}
catch
{
return false;
}
return true;
}
public static Image GetGooglePhoto(Synchronizer sync, Contact googleContact)
{
if (!HasPhoto(googleContact))
return null;
try
{
using (WebClient client = new WebClient())
{
//client.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + sync.ContactsRequest.Service.QueryClientLoginToken());
client.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + sync.ContactsRequest.Settings.OAuth2Parameters.AccessToken);
Stream stream = client.OpenRead(googleContact.PhotoUri.AbsoluteUri);
BinaryReader reader = new BinaryReader(stream);
Image image = Image.FromStream(stream);
reader.Close();
return image;
}
}
catch (Exception)
{
return null;
}
}
public static bool SetOutlookPhoto(Outlook.ContactItem outlookContact, string fullImagePath)
{
try
{
outlookContact.AddPicture(fullImagePath);
//outlookContact.Save();
return true;
}
catch
{
return false;
}
}
public static bool SetOutlookPhoto(Outlook.ContactItem outlookContact, Image image)
{
try
{
image.Save(tempPhotoPath);
return SetOutlookPhoto(outlookContact, tempPhotoPath);
}
catch
{
return false;
}
}
public static Image GetOutlookPhoto(Outlook.ContactItem outlookContact)
{
if (!HasPhoto(outlookContact))
return null;
try
{
foreach (Outlook.Attachment a in outlookContact.Attachments)
{
// CH Fixed this to Contains, due to outlook picture that looks like "ContactPicture_138382.jpg"
if (a.DisplayName.ToUpper().Contains("CONTACTPICTURE") || a.DisplayName.ToUpper().Contains("CONTACTPHOTO"))
{
//TODO: Check why always the first added picture is returned
//If you add another picture, still the old picture is saved to tempPhotoPath
a.SaveAsFile(tempPhotoPath);
return Image.FromFile(tempPhotoPath);
}
}
return null;
}
catch
{
// There's an error here... If Outlook says it has a contact photo, and we can't get it, Something's broken.
return null;
}
}
public static Image CropImageGoogleFormat(Image original)
{
// crop image to a square in the center
int width, height, diff;
Point p;
Rectangle r;
if (original.Height == original.Width)
return original;
if (original.Height > original.Width)
{
// tall image
width = original.Width;
height = width;
diff = original.Height - height;
p = new Point(0, diff / 2);
r = new Rectangle(p, new Size(width, height));
return CropImage(original, r);
}
else
{
// flat image
height = original.Height;
width = height;
diff = original.Width - width;
p = new Point(diff / 2, 0);
r = new Rectangle(p, new Size(width, height));
return CropImage(original, r);
}
}
public static Image CropImage(Image original, Rectangle cropArea)
{
using (Bitmap bmpImage = new Bitmap(original))
{
Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
return (Image)(bmpCrop);
}
}
public static void DeleteTempPhoto()
{
try
{
if (File.Exists(tempPhotoPath))
File.Delete(tempPhotoPath);
}
catch { }
}
public static bool ContainsGroup(Synchronizer sync, Contact googleContact, string groupName)
{
Group group = sync.GetGoogleGroupByName(groupName);
if (group == null)
return false;
return ContainsGroup(googleContact, group);
}
public static bool ContainsGroup(Contact googleContact, Group group)
{
foreach (GroupMembership m in googleContact.GroupMembership)
{
if (m.HRef == group.GroupEntry.Id.AbsoluteUri)
return true;
}
return false;
}
public static bool ContainsGroup(Outlook.ContactItem outlookContact, string group)
{
if (outlookContact.Categories == null)
return false;
return outlookContact.Categories.Contains(group);
}
public static Collection<Group> GetGoogleGroups(Synchronizer sync, Contact googleContact)
{
int c = googleContact.GroupMembership.Count;
Collection<Group> groups = new Collection<Group>();
string id;
Group group;
for (int i = 0; i < c; i++)
{
id = googleContact.GroupMembership[i].HRef;
group = sync.GetGoogleGroupById(id);
groups.Add(group);
}
return groups;
}
public static void AddGoogleGroup(Contact googleContact, Group group)
{
if (ContainsGroup(googleContact, group))
return;
GroupMembership m = new GroupMembership();
m.HRef = group.GroupEntry.Id.AbsoluteUri;
googleContact.GroupMembership.Add(m);
}
public static void RemoveGoogleGroup(Contact googleContact, Group group)
{
if (!ContainsGroup(googleContact, group))
return;
// TODO: broken. removes group membership but does not remove contact
// from group in the end.
// look for id
GroupMembership mem;
for (int i = 0; i < googleContact.GroupMembership.Count; i++)
{
mem = googleContact.GroupMembership[i];
if (mem.HRef == group.GroupEntry.Id.AbsoluteUri)
{
googleContact.GroupMembership.Remove(mem);
return;
}
}
throw new Exception("Did not find group");
}
public static string[] GetOutlookGroups(string outlookContactCategories)
{
if (outlookContactCategories == null)
return new string[] { };
char[] listseparator = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator.ToCharArray();
if (!outlookContactCategories.Contains(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator))
{// ListSeparator doesn't work always, because ListSeparator returns "," instead of ";"
listseparator = ",".ToCharArray();
if (!outlookContactCategories.Contains(","))
listseparator = ";".ToCharArray();
}
string[] categories = outlookContactCategories.Split(listseparator);
for (int i = 0; i < categories.Length; i++)
{
categories[i] = categories[i].Trim();
}
return categories;
}
public static void AddOutlookGroup(Outlook.ContactItem outlookContact, string group)
{
if (ContainsGroup(outlookContact, group))
return;
// append
if (outlookContact.Categories == null)
outlookContact.Categories = "";
if (!string.IsNullOrEmpty(outlookContact.Categories))
outlookContact.Categories += ", " + group;
else
outlookContact.Categories += group;
}
public static void RemoveOutlookGroup(Outlook.ContactItem outlookContact, string group)
{
if (!ContainsGroup(outlookContact, group))
return;
outlookContact.Categories = outlookContact.Categories.Replace(", " + group, "");
outlookContact.Categories = outlookContact.Categories.Replace(group, "");
}
//ToDo: Workaround to save google Content is also not working, beause of error when closing the StreamWriter
//public static bool SaveGoogleNoteContent(Syncronizer sync, Google.Documents.Document updated, Google.Documents.Document googleNote)
//{
// if (updated.DocumentEntry.EditUri == null || googleNote.MediaSource == null)
// throw new Exception("Must reload note from google.");
// StreamWriter writer = null;
// StreamReader reader = null;
// WebClient client = null;
// try
// {
// client = new WebClient();
// client.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + sync.DocumentsRequest.Service.QueryClientLoginToken());
// client.Headers.Add(HttpRequestHeader.ContentType, googleNote.MediaSource.ContentType);
// Stream s = client.OpenWrite(updated.DocumentEntry.EditUri.ToString(), "PUT");
// writer = new StreamWriter(s);
// reader = new StreamReader(googleNote.MediaSource.GetDataStream());
// string body = reader.ReadToEnd();
// writer.Write(body);
// }
// catch
// {
// return false;
// }
// finally
// {
// if (client != null)
// client.Dispose();
// if (writer != null)
// writer.Close(); //This throws an exception 400 (Ungültige Anforderung)
// if (reader != null)
// reader.Close();
// }
// return true;
//}
static public string ConvertToText(string rtf)
{
using (var rtb = new System.Windows.Forms.RichTextBox())
{
rtb.Rtf = rtf;
return rtb.Text;
}
}
static public string ConvertToText(byte[] rtf)
{
string ret = null;
if (rtf != null)
{
System.Text.Encoding encoding = new System.Text.ASCIIEncoding();
ret = encoding.GetString(rtf);
ret = ConvertToText(ret);
}
return ret;
}
}
public class OutlookFolder : IComparable
{
private string _folderName;
private string _folderID;
private bool _isDefaultFolder;
public OutlookFolder(string folderName, string folderID, bool isDefaultFolder)
{
_folderName = folderName;
_folderID = folderID;
_isDefaultFolder = isDefaultFolder;
}
public string FolderName
{
get
{
return _folderName;
}
}
public string FolderID
{
get
{
return _folderID;
}
}
public bool IsDefaultFolder
{
get
{
return _isDefaultFolder;
}
}
public string DisplayName
{
get
{
return _folderName + (_isDefaultFolder ? " (Default)" : String.Empty);
}
}
public int CompareTo(object obj)
{
if (obj == null) return 1;
OutlookFolder other = obj as OutlookFolder;
if (other == null)
{
throw new ArgumentException(string.Format("Cannot compare {0} with {1}", GetType().ToString(), obj.GetType().ToString()));
}
return CompareTo(this, other);
}
public static bool operator <(OutlookFolder left, OutlookFolder right)
{
if (ReferenceEquals(left, null))
{
if (ReferenceEquals(right, null))
return false;
else
return true;
}
else if (ReferenceEquals(right, null))
return false;
return CompareTo(left, right) < 0;
}
public static bool operator >(OutlookFolder left, OutlookFolder right)
{
if (ReferenceEquals(left, null))
{
if (ReferenceEquals(right, null))
return false;
else
return false;
}
else if (ReferenceEquals(right, null))
return true;
return CompareTo(left, right) > 0;
}
public static bool operator ==(OutlookFolder left, OutlookFolder right)
{
if (ReferenceEquals(left, null))
{
if (ReferenceEquals(right, null))
return true;
else
return false;
}
else if (ReferenceEquals(right, null))
return false;
return Equals(left, right);
}
public static bool operator !=(OutlookFolder left, OutlookFolder right)
{
return !(left == right);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(obj, null) || (obj.GetType() != GetType())) return false;
return Equals(this, obj as OutlookFolder);
}
internal static bool Equals(OutlookFolder left, OutlookFolder right)
{
return (right._folderName == left._folderName) &&
(right._folderID == left._folderID) &&
(right._isDefaultFolder == left._isDefaultFolder);
}
internal static int CompareTo(OutlookFolder left, OutlookFolder right)
{
int _folderNameComparison = left._folderName.CompareTo(right._folderName);
if (_folderNameComparison != 0)
return _folderNameComparison;
int _folderIDComparison = left._folderID.CompareTo(right._folderID);
if (_folderIDComparison != 0)
return _folderIDComparison;
return left._isDefaultFolder.CompareTo(right._isDefaultFolder);
}
public override int GetHashCode()
{
return HashUtils.CombineHashCodes(_folderName.GetHashCode(), _folderID.GetHashCode(), _isDefaultFolder.GetHashCode());
}
public override string ToString()
{
if (this is OutlookFolder)
return FolderID;
else
return base.ToString();
}
}
public class GoogleCalendar : IComparable
{
private string _folderName;
private string _folderID;
private bool _isDefaultFolder;
public GoogleCalendar(string folderName, string folderID, bool isDefaultFolder)
{
_folderName = folderName;
_folderID = folderID;
_isDefaultFolder = isDefaultFolder;
}
public string FolderName
{
get
{
return _folderName;
}
}
public string FolderID
{
get
{
return _folderID;
}
}
public bool IsDefaultFolder
{
get
{
return _isDefaultFolder;
}
}
public string DisplayName
{
get
{
return _folderName + (_isDefaultFolder ? " (Default)" : String.Empty);
}
}
public int CompareTo(object obj)
{
if (obj == null) return 1;
GoogleCalendar other = obj as GoogleCalendar;
if (other == null)
{
throw new ArgumentException(string.Format("Cannot compare {0} with {1}", GetType().ToString(), obj.GetType().ToString()));
}
return CompareTo(this, other);
}
public static bool operator <(GoogleCalendar left, GoogleCalendar right)
{
if (ReferenceEquals(left, null))
{
if (ReferenceEquals(right, null))
return false;
else
return true;
}
else if (ReferenceEquals(right, null))
return false;
return CompareTo(left, right) < 0;
}
public static bool operator >(GoogleCalendar left, GoogleCalendar right)
{
if (ReferenceEquals(left, null))
{
if (ReferenceEquals(right, null))
return false;
else
return false;
}
else if (ReferenceEquals(right, null))
return true;
return CompareTo(left, right) > 0;
}
public static bool operator ==(GoogleCalendar left, GoogleCalendar right)
{
if (ReferenceEquals(left, null))
{
if (ReferenceEquals(right, null))
return true;
else
return false;
}
else if (ReferenceEquals(right, null))
return false;
return Equals(left, right);
}
public static bool operator !=(GoogleCalendar left, GoogleCalendar right)
{
return !(left == right);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(obj, null) || (obj.GetType() != GetType())) return false;
return Equals(this, obj as OutlookFolder);
}
internal static bool Equals(GoogleCalendar left, GoogleCalendar right)
{
return (right._folderName == left._folderName) &&
(right._folderID == left._folderID) &&
(right._isDefaultFolder == left._isDefaultFolder);
}
internal static int CompareTo(GoogleCalendar left, GoogleCalendar right)
{
int _folderNameComparison = left._folderName.CompareTo(right._folderName);
if (_folderNameComparison != 0)
return _folderNameComparison;
int _folderIDComparison = left._folderID.CompareTo(right._folderID);
if (_folderIDComparison != 0)
return _folderIDComparison;
return left._isDefaultFolder.CompareTo(right._isDefaultFolder);
}
public override int GetHashCode()
{
return HashUtils.CombineHashCodes(_folderName.GetHashCode(), _folderID.GetHashCode(), _isDefaultFolder.GetHashCode());
}
public override string ToString()
{
if (this is GoogleCalendar)
return FolderID;
else
return base.ToString();
}
}
//Taken from Tuple
public static class HashUtils
{
public static int CombineHashCodes(int h1, int h2)
{
return (((h1 << 5) + h1) ^ h2);
}
public static int CombineHashCodes(int h1, int h2, int h3)
{
return CombineHashCodes(CombineHashCodes(h1, h2), h3);
}
}
}
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.