Menu

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

Download this file

566 lines (486 with data), 18.8 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
using Dangl.TextConverter.Rtf;
using Google.Apis.PeopleService.v1.Data;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.IO;
using System.Net;
using Outlook = Microsoft.Office.Interop.Outlook;
using Serilog;
namespace GoContactSyncMod
{
internal static class Utilities
{
public static string GetTempFileName(string ext)
{
var fileName = Path.GetRandomFileName();
fileName = Path.ChangeExtension(fileName, ext);
fileName = Path.Combine(Path.GetTempPath(), fileName);
return fileName;
}
public static byte[] BitmapToBytes(Bitmap bmp)
{
//bitmap
using (var stream = new MemoryStream())
{
bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
return stream.ToArray();
}
}
public static bool HasContactPhoto(Person gc)
{
if (gc.Photos != null)
foreach (var photo in gc.Photos)
{
if (!photo.Metadata.Source.Type.Equals(ContactPropertiesUtils.CONTACT, StringComparison.OrdinalIgnoreCase))
continue; //photo is not a contact photo (e.g. profile photo), skipping.
var isDefaultPhoto = photo.Default__ ?? false;
if (isDefaultPhoto) //don'T consider a default avatar photo as real Google contact photo
{
Log.Debug($"Google Contact has no contact photo!");
return false;
}
}
Log.Debug($"Google Contact has a contact photo!");
return true;
}
//public static bool SaveGooglePhoto(Synchronizer sync, Person gc, Image image)
//{
// if (gc.ContactEntry.PhotoUri == null)
// {
// throw new Exception("Must reload contact from google.");
// }
// try
// {
// using (var client = new WebClient())
// {
// //client.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + sync.PeopleRequest.Settings.OAuth2Parameters.AccessToken);//ToDo: Check, how to get the AccessToken from new PeopleAPI
// client.Headers.Add(HttpRequestHeader.ContentType, "image/*");
// using (var pic = new Bitmap(image))
// {
// using (var s = client.OpenWrite(gc.ContactEntry.PhotoUri.AbsoluteUri, "PUT"))
// {
// var bytes = BitmapToBytes(pic);
// s.Write(bytes, 0, bytes.Length);
// s.Flush();
// }
// }
// }
// }
// catch
// {
// return false;
// }
// return true;
//}
public static Image GetGoogleContactPhoto(Synchronizer sync, Person gc)
{
try
{
Photo photo = null;
foreach (var ph in gc.Photos)
{
if (!ph.Metadata.Source.Type.Equals(ContactPropertiesUtils.CONTACT, StringComparison.OrdinalIgnoreCase))
continue; //photo is not a contact photo (e.g. profile photo), try next.
var isDefaultPhoto = ph.Default__ ?? false;
if (!isDefaultPhoto)
{
photo = ph;
break;
}
}
if (photo != null)
{
using (var client = new WebClient())
{
client.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + sync.GooglePeopleRequest.AccessToken); //ToDo: Check, if works from new PeopleAPI, seems to work (big-r, 08.07.2021)!
var stream = client.OpenRead(photo.Url);
var reader = new BinaryReader(stream);
var image = Image.FromStream(stream);
reader.Close();
return image;
}
}
}
catch (Exception ex)
{
Log.Error(ex, $"Error fetching Google contact photo: {ex}");
}
return null;
}
public static Image CropImageGoogleFormat(Image original)
{
// crop image to a square in the center
if (original.Height == original.Width)
{
return original;
}
if (original.Height > original.Width)
{
// tall image
var width = original.Width;
var height = width;
var diff = original.Height - height;
var p = new Point(0, diff / 2);
var r = new Rectangle(p, new Size(width, height));
return CropImage(original, r);
}
else
{
// flat image
var height = original.Height;
var width = height;
var diff = original.Width - width;
var p = new Point(diff / 2, 0);
var r = new Rectangle(p, new Size(width, height));
return CropImage(original, r);
}
}
public static Image CropImage(Image original, Rectangle cropArea)
{
using (var bmpImage = new Bitmap(original))
{
var bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
return bmpCrop;
}
}
public static bool ContainsGroup(Synchronizer sync, Person gc, string groupName)
{
var group = sync.GetGoogleGroupByName(groupName);
return group != null && ContainsGroup(gc, group);
}
public static bool ContainsGroup(Person gc, ContactGroup group)
{
if (gc.Memberships != null)
foreach (var m in gc.Memberships)
{
if (m.ContactGroupMembership != null && m.ContactGroupMembership.ContactGroupResourceName == group.ResourceName)
{
return true;
}
}
return false;
}
public static bool ContainsGroup(Outlook.ContactItem oc, string group)
{
return oc.Categories != null && oc.Categories.Contains(group);
}
public static Collection<ContactGroup> GetGoogleGroups(Synchronizer sync, Person gc)
{
var groups = new Collection<ContactGroup>();
if (gc.Memberships != null && gc.Memberships.Count > 0)
foreach (var group in gc.Memberships)
if (group != null && group.ContactGroupMembership != null && group.ContactGroupMembership.ContactGroupResourceName != Synchronizer.myContactsGroup)
{
var g = sync.GetGoogleGroupByResourceName(group.ContactGroupMembership.ContactGroupResourceName);
if (g != null)
groups.Add(g);
}
return groups;
}
public static void AddGoogleGroup(Person gc, ContactGroup group)
{
if (ContainsGroup(gc, group))
{
return;
}
var m = new Membership()
{
ContactGroupMembership = new ContactGroupMembership()
{
ContactGroupResourceName = group.ResourceName
}
//HRef = group.GroupEntry.Id.AbsoluteUri;
};
if (gc.Memberships == null)
gc.Memberships = new List<Membership>();
gc.Memberships.Add(m);
}
public static void RemoveGoogleGroup(Person gc, ContactGroup group)
{
if (!ContainsGroup(gc, group))
{
return;
}
// TODO: broken. removes group membership but does not remove contact
// from group in the end.
// look for id
Membership mem;
for (var i = 0; i < gc.Memberships.Count; i++)
{
mem = gc.Memberships[i];
if (mem.ContactGroupMembership != null && mem.ContactGroupMembership.ContactGroupResourceName == group.ResourceName) //Todo: Check
{
gc.Memberships.Remove(mem);
return;
}
}
throw new Exception("Did not find group");
}
public static string[] GetOutlookGroups(string outlookContactCategories)
{
if (outlookContactCategories == null)
{
return new string[] { };
}
var 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();
}
}
var categories = outlookContactCategories.Split(listseparator);
for (var i = 0; i < categories.Length; i++)
{
categories[i] = categories[i].Trim();
}
return categories;
}
public static void AddOutlookGroup(Outlook.ContactItem oc, string group)
{
if (ContainsGroup(oc, group))
{
return;
}
// append
if (oc.Categories == null)
{
oc.Categories = "";
}
if (!string.IsNullOrEmpty(oc.Categories))
{
oc.Categories += ", " + group;
}
else
{
oc.Categories += group;
}
}
public static void RemoveOutlookGroup(Outlook.ContactItem oc, string group)
{
if (!ContainsGroup(oc, group))
{
return;
}
oc.Categories = oc.Categories.Replace(", " + group, "");
oc.Categories = oc.Categories.Replace(group, "");
}
public static string ConvertToText(string rtf)
{
return RtfToText.ConvertRtfToText(rtf);
}
public static string ConvertToText(byte[] rtf)
{
if (rtf != null)
{
var encoding = new System.Text.ASCIIEncoding();
return ConvertToText(encoding.GetString(rtf));
}
return string.Empty;
}
}
public class OutlookFolder : IComparable
{
public OutlookFolder(string folderName, string folderID, bool isDefaultFolder)
{
FolderName = folderName;
FolderID = folderID;
IsDefaultFolder = isDefaultFolder;
}
public string FolderName { get; }
public string FolderID { get; }
public bool IsDefaultFolder { get; }
public string DisplayName => FolderName + (IsDefaultFolder ? " (Default)" : string.Empty);
public int CompareTo(object obj)
{
if (obj == null)
{
return 1;
}
var other = obj as OutlookFolder;
if (other == null)
{
throw new ArgumentException($"Cannot compare {GetType()} with {obj.GetType()}");
}
return CompareTo(this, other);
}
public static bool operator <(OutlookFolder left, OutlookFolder right)
{
if (left is null)
{
return !(right is null);
}
else if (right is null)
{
return false;
}
return CompareTo(left, right) < 0;
}
public static bool operator >(OutlookFolder left, OutlookFolder right)
{
if (left is null)
{
return right is null;
}
else if (right is null)
{
return true;
}
return CompareTo(left, right) > 0;
}
public static bool operator ==(OutlookFolder left, OutlookFolder right)
{
if (left is null)
{
return right is null;
}
else if (right is null)
{
return false;
}
return Equals(left, right);
}
public static bool operator !=(OutlookFolder left, OutlookFolder right)
{
return !(left == right);
}
public override bool Equals(object obj)
{
return !(obj is null) && obj.GetType() == GetType() && 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)
{
var _folderNameComparison = left.FolderName.CompareTo(right.FolderName);
if (_folderNameComparison != 0)
{
return _folderNameComparison;
}
var _folderIDComparison = left.FolderID.CompareTo(right.FolderID);
return _folderIDComparison != 0 ? _folderIDComparison : left.IsDefaultFolder.CompareTo(right.IsDefaultFolder);
}
public override int GetHashCode()
{
return HashUtils.CombineHashCodes(FolderName.GetHashCode(), FolderID.GetHashCode(), IsDefaultFolder.GetHashCode());
}
public override string ToString()
{
return this is OutlookFolder ? FolderID : base.ToString();
}
}
public class GoogleCalendar : IComparable
{
public GoogleCalendar(string folderName, string folderID, bool isDefaultFolder)
{
FolderName = folderName;
FolderID = folderID;
IsDefaultFolder = isDefaultFolder;
}
public string FolderName { get; }
public string FolderID { get; }
public bool IsDefaultFolder { get; }
public string DisplayName => FolderName + (IsDefaultFolder ? " (Default)" : string.Empty);
public int CompareTo(object obj)
{
if (obj == null)
{
return 1;
}
var other = obj as GoogleCalendar;
if (other == null)
{
throw new ArgumentException($"Cannot compare {GetType()} with {obj.GetType()}");
}
return CompareTo(this, other);
}
public static bool operator <(GoogleCalendar left, GoogleCalendar right)
{
if (left is null)
{
return !(right is null);
}
else if (right is null)
{
return false;
}
return CompareTo(left, right) < 0;
}
public static bool operator >(GoogleCalendar left, GoogleCalendar right)
{
if (left is null)
{
return right is null && false;
}
else if (right is null)
{
return true;
}
return CompareTo(left, right) > 0;
}
public static bool operator ==(GoogleCalendar left, GoogleCalendar right)
{
if (left is null)
{
return right is null;
}
else if (right is null)
{
return false;
}
return Equals(left, right);
}
public static bool operator !=(GoogleCalendar left, GoogleCalendar right)
{
return !(left == right);
}
public override bool Equals(object obj)
{
return !(obj is null) && obj.GetType() == GetType() && 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)
{
var _folderNameComparison = left.FolderName.CompareTo(right.FolderName);
if (_folderNameComparison != 0)
{
return _folderNameComparison;
}
var _folderIDComparison = left.FolderID.CompareTo(right.FolderID);
return _folderIDComparison != 0 ? _folderIDComparison : left.IsDefaultFolder.CompareTo(right.IsDefaultFolder);
}
public override int GetHashCode()
{
return HashUtils.CombineHashCodes(FolderName.GetHashCode(), FolderID.GetHashCode(), IsDefaultFolder.GetHashCode());
}
public override string ToString()
{
return this is GoogleCalendar ? FolderID : 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.