~iwarford/do-plugins/fart-plugin-fwiw

« back to all changes in this revision

Viewing changes to RememberTheMilk/src/RTM.cs

  • Committer: Jason Jones
  • Date: 2008-12-24 04:45:02 UTC
  • mfrom: (335.1.9 do-plugins)
  • Revision ID: jasonedwardjones@gmail.com-20081224044502-ra56ym06cp1iqs7t
MergedĀ fromĀ trunk.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* RTM.cs
 
2
 *
 
3
 * GNOME Do is the legal property of its developers. Please refer to the
 
4
 * COPYRIGHT file distributed with this
 
5
 * source distribution.
 
6
 *
 
7
 * This program is free software: you can redistribute it and/or modify
 
8
 * it under the terms of the GNU General Public License as published by
 
9
 * the Free Software Foundation, either version 3 of the License, or
 
10
 * (at your option) any later version.
 
11
 *
 
12
 * This program is distributed in the hope that it will be useful,
 
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
15
 * GNU General Public License for more details.
 
16
 *
 
17
 * You should have received a copy of the GNU General Public License
 
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
19
 */
 
20
 
 
21
using System;
 
22
using System.Collections.Generic;
 
23
using System.Text.RegularExpressions;
 
24
using Mono.Unix;
 
25
using RtmNet;
 
26
 
 
27
 
 
28
using Do.Universe;
 
29
 
 
30
 
 
31
namespace Do.Addins.RTM
 
32
{
 
33
    public static class RTM
 
34
    {
 
35
        private static Rtm rtm;
 
36
        private static Dictionary<string,List<Item>> tasks;
 
37
        private static Dictionary<string,Item> lists;
 
38
        private static object lists_lock;
 
39
        private static object lists_lock_at;
 
40
        private static object dict_lock;
 
41
        private static string timeline;
 
42
        private static DateTime last_sync;
 
43
        private static string username;
 
44
                private static string filter;
 
45
                
 
46
 
 
47
        private const string api_key = "ee32c06f2d45baf935a2c046323457d8";
 
48
        private const string shared_secret = "1b835b123a903938";
 
49
 
 
50
        static RTM ()
 
51
        {
 
52
            rtm = new Rtm (api_key, shared_secret);
 
53
            tasks = new Dictionary<string,List<Item>> ();
 
54
            lists = new Dictionary<string,Item> ();
 
55
            lists_lock = new object ();
 
56
            lists_lock_at = new object ();
 
57
            dict_lock = new object ();
 
58
            last_sync = DateTime.MinValue;
 
59
                        filter = Configuration.Filter;
 
60
                        
 
61
            if (!String.IsNullOrEmpty (Configuration.AuthToken)) {
 
62
                Auth auth;
 
63
                try {
 
64
                    auth = rtm.AuthCheckToken (Configuration.AuthToken);
 
65
                } catch (RtmException e) {
 
66
                    Console.Error.WriteLine ("Token verification failed: " + e.Message);
 
67
                    return;
 
68
                }
 
69
                rtm.AuthToken = auth.Token;
 
70
                timeline = rtm.TimelineCreate ();
 
71
                username = auth.User.Username;
 
72
            }
 
73
        }
 
74
 
 
75
        public static string Username {
 
76
            get { return username; }
 
77
        }
 
78
 
 
79
        public static bool IsAuthenticated {
 
80
            get { return  (rtm.IsAuthenticated && !String.IsNullOrEmpty (rtm.AuthToken)); }
 
81
        }
 
82
 
 
83
        public static string AuthInit ()
 
84
        {
 
85
            string frob;
 
86
            try {
 
87
                frob = rtm.AuthGetFrob ();
 
88
            } catch (RtmException e) {
 
89
                Console.Error.WriteLine ("Fail to initialize authentication: " + e.Message);
 
90
                return "";
 
91
            }
 
92
            Do.Platform.Services.Environment.OpenUrl(rtm.AuthCalcUrl (frob, AuthLevel.Delete));
 
93
            return frob;
 
94
        }
 
95
 
 
96
        public static Auth AuthComplete (string frob)
 
97
        {
 
98
            Auth auth;
 
99
            try {
 
100
                auth = rtm.AuthGetToken (frob);
 
101
            } catch (RtmException e) {
 
102
                Console.Error.WriteLine ("Fails to complete authentication: " + e.Message);
 
103
                return null;
 
104
            }
 
105
            rtm.AuthToken = auth.Token;
 
106
            timeline = rtm.TimelineCreate ();
 
107
            return auth;
 
108
        }
 
109
 
 
110
        public static List<Item> Lists {
 
111
            get {
 
112
                List<Item> lists2 = new List<Item> ();
 
113
                lists2.Clear ();
 
114
                lists2.Add (new RTMListItem ("All Tasks", "All Tasks"));
 
115
 
 
116
                lock (dict_lock)
 
117
                    foreach (KeyValuePair<string,Item> kvp in lists)
 
118
                        lists2.Add (kvp.Value);
 
119
 
 
120
                return lists2;
 
121
            }
 
122
        }
 
123
 
 
124
        public static void UpdateLists ()
 
125
        {
 
126
                        if (!IsAuthenticated)
 
127
                                return;
 
128
                        
 
129
            Lists rtmLists;
 
130
            try {
 
131
                rtmLists = rtm.ListsGetList ();
 
132
            } catch (RtmException e) {
 
133
                Console.Error.WriteLine (e.Message);
 
134
                rtmLists = null;
 
135
                return;
 
136
            }
 
137
 
 
138
            lists.Clear ();
 
139
            foreach (List rtmList in rtmLists.listCollection)
 
140
                if (rtmList.Deleted == 0 && rtmList.Smart == 0)
 
141
                    lists [rtmList.ID] = new RTMListItem (rtmList.ID, rtmList.Name);
 
142
        }
 
143
 
 
144
        public static List<Item> TasksForList (string listId)
 
145
        {
 
146
            return tasks [listId];
 
147
        }
 
148
 
 
149
        public static string ListNameForList (string listId)
 
150
        {
 
151
            return lists [listId].Name;
 
152
        }
 
153
 
 
154
        public static void UpdateTasks ()
 
155
        {
 
156
 
 
157
                        if (!IsAuthenticated)
 
158
                                return;
 
159
                        
 
160
            Tasks rtmTasks;
 
161
                        
 
162
                        // if settings have changed, reset the synchronization state;
 
163
                        if (filter != Configuration.Filter || username != Configuration.Username)
 
164
                                last_sync = DateTime.MinValue;
 
165
 
 
166
            if (last_sync == DateTime.MinValue) {
 
167
                tasks.Clear ();
 
168
                tasks ["All Tasks"] = new List<Item> ();
 
169
            }
 
170
                        
 
171
                        filter = Configuration.Filter;
 
172
                        if (String.IsNullOrEmpty (filter))
 
173
                                filter = "status:incomplete";                           
 
174
                        else if (!filter.Contains ("status:"))
 
175
                                filter = "status:incomplete OR (" + filter + ")";
 
176
                        
 
177
            try {
 
178
                // If first time sync, get full list of incompleted tasks
 
179
                // otherwise, only do incremental sync.
 
180
                if (last_sync == DateTime.MinValue)
 
181
                    rtmTasks = rtm.TasksGetList (null, null, filter);
 
182
                else
 
183
                    rtmTasks = rtm.TasksGetList (null, last_sync.ToUniversalTime ().ToString ("u"), filter);
 
184
            } catch (RtmException e) {
 
185
                rtmTasks = null;
 
186
                                last_sync = DateTime.MinValue;
 
187
                Console.Error.WriteLine (e.Message);
 
188
                return;
 
189
            }
 
190
 
 
191
            foreach (List rtmList in rtmTasks.ListCollection) {
 
192
                if (!tasks.ContainsKey (rtmList.ID))
 
193
                    tasks [rtmList.ID] = new List<Item> ();
 
194
 
 
195
                if (rtmList.DeletedTaskSeries != null)
 
196
                    foreach (TaskSeries rtmTaskSeries in rtmList.DeletedTaskSeries.TaskSeriesCollection)
 
197
                        foreach (Task rtmTask in rtmTaskSeries.TaskCollection)
 
198
                            UniverseRemoveTask (rtmTask.TaskID, rtmList.ID);
 
199
 
 
200
                if (rtmList.TaskSeriesCollection != null) {
 
201
                    foreach (TaskSeries rtmTaskSeries in rtmList.TaskSeriesCollection) {
 
202
                                                foreach (Task rtmTask in rtmTaskSeries.TaskCollection) {
 
203
                                                        // delete one recurrent task will cause other deleted instances
 
204
                                                        // appear in the taskseries tag, so here we need to check again.
 
205
                                                        if (rtmTask.Deleted == DateTime.MinValue) {
 
206
                                                                tasks [rtmList.ID].Add (new RTMTaskItem (rtmList.ID, rtmTaskSeries.TaskSeriesID,
 
207
                                                                                                         rtmTask.TaskID, rtmTaskSeries.Name,
 
208
                                                                                                         rtmTask.Due, rtmTask.Completed, rtmTask.Priority,
 
209
                                                                                                         rtmTask.HasDueTime));
 
210
                                                                tasks ["All Tasks"].Add (new RTMTaskItem (rtmList.ID, rtmTaskSeries.TaskSeriesID,
 
211
                                                                                                          rtmTask.TaskID, rtmTaskSeries.Name,
 
212
                                                                                                          rtmTask.Due, rtmTask.Completed, rtmTask.Priority,
 
213
                                                                                                          rtmTask.HasDueTime));
 
214
                                                        }
 
215
                        }
 
216
                    }
 
217
                }
 
218
            }
 
219
 
 
220
            last_sync = DateTime.Now;
 
221
                        
 
222
                        if (Configuration.OverdueNotification)
 
223
                                NotifyOverDueItems ();
 
224
        }
 
225
 
 
226
                /// <summary>
 
227
                /// Remove task identified by taskId from list identified by listId
 
228
                /// and from 'All Tasks' list
 
229
                /// </summary>
 
230
                /// <param name="taskId">
 
231
                /// A <see cref="System.String"/>, to identify the task to remove
 
232
                /// </param>
 
233
                /// <param name="listId">
 
234
                /// A <see cref="System.String"/>, to identify the list from which to remove
 
235
                /// the task
 
236
                /// </param>
 
237
        private static void UniverseRemoveTask (string taskId, string listId)
 
238
        {
 
239
            lock (lists_lock) {
 
240
                foreach (RTMTaskItem task in tasks [listId].ToArray ())
 
241
                    if (task.Id == taskId)
 
242
                        tasks [listId].Remove (task);
 
243
            }
 
244
 
 
245
            lock (lists_lock_at) {
 
246
                foreach (RTMTaskItem task in tasks ["All Tasks"].ToArray ())
 
247
                    if (task.Id == taskId)
 
248
                        tasks ["All Tasks"].Remove (task);
 
249
            }
 
250
        }
 
251
 
 
252
                /// <summary>
 
253
                /// Check if there is overdue task in All Tasks list,
 
254
                /// when user chooses to be notified, display the information.
 
255
                /// </summary>
 
256
        private static void NotifyOverDueItems ()
 
257
        {
 
258
            List<string> overdue_tasks;
 
259
            overdue_tasks = new List<string> ();
 
260
            lock (lists_lock_at) {
 
261
                foreach (RTMTaskItem task in tasks ["All Tasks"].ToArray ())
 
262
                                        if ((task.Completed == DateTime.MinValue) && (task.Due > DateTime.MinValue) &&
 
263
                                            ((task.Due < DateTime.Now && task.HasDueTime == 1) || task.Due.Date < DateTime.Today))
 
264
                                                overdue_tasks.Add (task.Name);
 
265
            }
 
266
 
 
267
                        int len = overdue_tasks.ToArray ().Length;
 
268
                        if ( len > 0 && Configuration.OverdueNotification) {
 
269
                                string title;
 
270
                                title = String.Format (Catalog.GetPluralString ("{0} Task Overdue", 
 
271
                                                                                "{0} Tasks Overdue", len), len);
 
272
//                              if (len > 1)
 
273
//                                      title = Catalog.GetString (String.Format ("{0} Tasks overdue", len));
 
274
//                              else
 
275
//                                      title = Catalog.GetString ("1 Task Overdue");
 
276
                                
 
277
                                string body = "";
 
278
                                foreach (string name in overdue_tasks) // TODO: missing lock
 
279
                                        body += ("- " + name +"\n");
 
280
                                
 
281
                                Do.Platform.Services.Notifications.Notify(new Do.Platform.Notification( title, body, "task-overdue.png@" + typeof(RTMTaskItem).Assembly.FullName ) );
 
282
                        }
 
283
        }               
 
284
                                
 
285
                /// <summary>
 
286
                /// A wrapper function to complete several common tasks for most action methods:
 
287
                /// 1. display notification if user choose to
 
288
                /// 2. clear modified task from its list and 'All Tasks' list
 
289
                /// 3. update tasks
 
290
                /// </summary>
 
291
                /// <param name="title">
 
292
                /// A <see cref="System.String"/> for the title of the notification message.
 
293
                /// </param>
 
294
                /// <param name="body">
 
295
                /// A <see cref="System.String"/> for the content of the notification message. 
 
296
                /// </param>
 
297
                /// <param name="taskId">
 
298
                /// A <see cref="System.String"/>, if exist, will be passed to <see cref="UniverseRemoveTask"/>
 
299
                /// </param>
 
300
                /// <param name="listId">
 
301
                /// A <see cref="System.String"/>, if exist, will be passed to <see cref="UniverseRemoveTask"/>
 
302
                /// </param>
 
303
                private static void ActionRoutine (string title, string body, string taskId, string listId)
 
304
                {
 
305
                        if (Configuration.ActionNotification) {
 
306
                                Do.Platform.Services.Notifications.Notify( new Do.Platform.Notification( title, body, 
 
307
                                                                                                        "task.png@" + typeof(RTMTaskItem).Assembly.FullName ) );
 
308
                        }
 
309
                        if (taskId != null && listId != null)
 
310
                                UniverseRemoveTask (taskId, listId);
 
311
                        UpdateTasks ();
 
312
                }
 
313
 
 
314
        public static RTMTaskItem NewTask (string listId, string taskData)
 
315
        {
 
316
            List rtmList;
 
317
            bool parse = true;
 
318
            string priority = "N";
 
319
 
 
320
                        // Task string starting with "@" won't be parsed for date/time information
 
321
                        if (taskData.StartsWith ("@")) {
 
322
                taskData = taskData.Remove (0, 1).Trim ();
 
323
                parse = false;
 
324
            }
 
325
 
 
326
                        // Task string starting with "![123]" contains priority information
 
327
                        if (Regex.IsMatch (taskData, @"^![123]\s")) {
 
328
                priority = taskData.Substring (1,1);
 
329
                taskData = taskData.Remove (0, 3);
 
330
            }
 
331
 
 
332
            try {
 
333
                rtmList = rtm.TasksAdd (timeline, taskData, listId, parse);
 
334
            } catch (RtmException e) {
 
335
                Console.Error.WriteLine (e.Message);
 
336
                return null;
 
337
            }
 
338
 
 
339
 
 
340
            if (priority != "N") {
 
341
                try {
 
342
                    rtm.TasksSetPriority (timeline, rtmList.ID, 
 
343
                                                              rtmList.TaskSeriesCollection[0].TaskSeriesID,
 
344
                                          rtmList.TaskSeriesCollection[0].TaskCollection[0].TaskID, 
 
345
                                                              priority);
 
346
                } catch (RtmException e) {
 
347
                    Console.Error.WriteLine (e.Message);
 
348
                }
 
349
            }
 
350
 
 
351
            UpdateTasks ();
 
352
            return new RTMTaskItem (rtmList.ID, rtmList.TaskSeriesCollection[0].TaskSeriesID,
 
353
                                    rtmList.TaskSeriesCollection[0].TaskCollection[0].TaskID,
 
354
                                    rtmList.TaskSeriesCollection[0].Name,
 
355
                                    rtmList.TaskSeriesCollection[0].TaskCollection[0].Due, 
 
356
                                                rtmList.TaskSeriesCollection[0].TaskCollection[0].Completed, 
 
357
                                                priority,
 
358
                                    rtmList.TaskSeriesCollection[0].TaskCollection[0].HasDueTime);
 
359
        }
 
360
 
 
361
        public static void DeleteTask (string listId, string taskSeriesId, string taskId)
 
362
        {
 
363
            try {
 
364
                rtm.TasksDelete (timeline, listId, taskSeriesId, taskId);
 
365
            } catch (RtmException e) {
 
366
                Console.Error.WriteLine (e.Message);
 
367
                return;
 
368
            }
 
369
 
 
370
            ActionRoutine (Catalog.GetString ("Task Deleted"),
 
371
                                       Catalog.GetString ("The selected task has been successfully deleted"
 
372
                                                          +" from your Remember The Milk task list"),
 
373
                                       null, null);
 
374
        }
 
375
 
 
376
        public static void CompleteTask (string listId, string taskSeriesId, string taskId)
 
377
        {
 
378
            try {
 
379
                rtm.TasksComplete (timeline, listId, taskSeriesId, taskId);
 
380
            } catch (RtmException e) {
 
381
                Console.Error.WriteLine (e.Message);
 
382
                return;
 
383
            }
 
384
 
 
385
            ActionRoutine (Catalog.GetString ("Task Completed"),
 
386
                                       Catalog.GetString ("The selected task in your Remember The Milk"
 
387
                                                          +" task list has been marked as completed."),
 
388
                                       taskId, listId);
 
389
        }
 
390
                
 
391
        public static List<Item> GeneratePriorities ()
 
392
        {
 
393
            List<Item> priorities = new List<Item> ();
 
394
            priorities.Add (new RTMPriorityItem (Catalog.GetString ("High"), 
 
395
                                                             Catalog.GetString ("High Priority")));
 
396
            priorities.Add (new RTMPriorityItem (Catalog.GetString ("Medium"), 
 
397
                                                             Catalog.GetString ("Medium Priority")));
 
398
            priorities.Add (new RTMPriorityItem (Catalog.GetString ("Low"), 
 
399
                                                             Catalog.GetString ("Low Priority")));
 
400
            priorities.Add (new RTMPriorityItem (Catalog.GetString ("None"), 
 
401
                                                             Catalog.GetString ("No Priority")));
 
402
            priorities.Add (new RTMPriorityItem (Catalog.GetString ("Up"), 
 
403
                                                             Catalog.GetString ("Increase the priority")));
 
404
            priorities.Add (new RTMPriorityItem (Catalog.GetString ("Down"), 
 
405
                                                             Catalog.GetString ("Decrease the priority")));
 
406
            return priorities;
 
407
        }
 
408
 
 
409
        public static void SetTaskPriority (string listId, string taskSeriesId, string taskId, string priority)
 
410
        {
 
411
            try {
 
412
                if (priority == "up" || priority == "down")
 
413
                    rtm.TasksMovePriority (timeline, listId, taskSeriesId, taskId, priority);
 
414
                else
 
415
                    rtm.TasksSetPriority (timeline, listId, taskSeriesId, taskId, priority);
 
416
            } catch (RtmException e) {
 
417
                Console.Error.WriteLine (e.Message);
 
418
                return;
 
419
            }
 
420
 
 
421
            ActionRoutine (Catalog.GetString ("Priority Changed"),
 
422
                                       Catalog.GetString ("The priority of the selected task in your"
 
423
                                                          +" Remember The Milk task list has been changed."),
 
424
                                       taskId, listId);
 
425
        }
 
426
 
 
427
        public static void SetDueDateTime (string listId, string taskSeriesId, string taskId, string due)
 
428
        {
 
429
            try {
 
430
                if (String.IsNullOrEmpty (due))
 
431
                                        rtm.TasksSetDueDate (timeline, listId, taskSeriesId, taskId);
 
432
                                else
 
433
                                        rtm.TasksSetDueDateParse (timeline, listId, taskSeriesId, taskId, due);
 
434
            } catch (RtmException e) {
 
435
                Console.Error.WriteLine (e.Message);
 
436
                return;
 
437
            }
 
438
 
 
439
            ActionRoutine (Catalog.GetString ("Due Date/Time Changed"),
 
440
                                       Catalog.GetString ("The due date/time of the selected task in your "
 
441
                                                          +"Remember The Milk task list has been changed."),
 
442
                                       taskId, listId);
 
443
        }
 
444
 
 
445
        public static void MoveTask (string fromListId, string toListId, string taskSeriesId, string taskId)
 
446
        {
 
447
            try {
 
448
                rtm.TasksMoveTo (timeline, fromListId, toListId, taskSeriesId, taskId);
 
449
            } catch (RtmException e) {
 
450
                Console.Error.WriteLine (e.Message);
 
451
                return;
 
452
            }
 
453
 
 
454
            ActionRoutine (Catalog.GetString ("Task Moved"),
 
455
                                       Catalog.GetString (String.Format ("The selected task has been moved from"
 
456
                                                                        + " Remember The Milk list \"{0}\" to list \"{1}\".",
 
457
                                                                        lists [fromListId].Name, lists [toListId].Name)),
 
458
                                       taskId, fromListId);
 
459
        }
 
460
 
 
461
        public static void RenameTask (string listId, string taskSeriesId, string taskId, string newName)
 
462
        {
 
463
            try {
 
464
                rtm.TasksSetName (timeline, listId, taskSeriesId, taskId, newName);
 
465
            } catch (RtmException e) {
 
466
                Console.Error.WriteLine (e.Message);
 
467
                return;
 
468
            }
 
469
 
 
470
            ActionRoutine (Catalog.GetString ("Task Renamed"),
 
471
                                       Catalog.GetString (String.Format ("The selected task has"
 
472
                                                                        + " been renamed to \"{0}\".", newName)),
 
473
                                       taskId, listId);
 
474
        }
 
475
 
 
476
        public static void PostponeTask (string listId, string taskSeriesId, string taskId)
 
477
        {
 
478
            try {
 
479
                rtm.TasksPostpone (timeline, listId, taskSeriesId, taskId);
 
480
            } catch (RtmException e) {
 
481
                Console.Error.WriteLine (e.Message);
 
482
                return;
 
483
            }
 
484
 
 
485
            ActionRoutine (Catalog.GetString ("Task Postponed"),
 
486
                                       Catalog.GetString ("The selected task in your Remember The Milk task"
 
487
                                                          + " list has been postponed"),
 
488
                                       taskId, listId);
 
489
                }
 
490
 
 
491
        public static void SetRecurrence (string listId, string taskSeriesId, string taskId, string repeat)
 
492
        {
 
493
                        try {
 
494
                                rtm.TasksSetRecurrence (timeline, listId, taskSeriesId, taskId, repeat);
 
495
            } catch (RtmException e) {
 
496
                Console.Error.WriteLine (e.Message);
 
497
                return;
 
498
            }
 
499
 
 
500
            ActionRoutine (Catalog.GetString ("Recurrence Pattern Changed"),
 
501
                                       Catalog.GetString ("The recurrence pattern of the selected task in your"
 
502
                                                          + " Remember The Milk task list has been changed."), 
 
503
                                       taskId, listId);
 
504
        }
 
505
                
 
506
                public static void UncompleteTask (string listId, string taskSeriesId, string taskId)
 
507
                {
 
508
                        try {
 
509
                                rtm.TasksUncomplete (timeline, listId, taskSeriesId, taskId);
 
510
                        } catch (RtmException e) {
 
511
                                Console.Error.WriteLine (e.Message);
 
512
                                return;
 
513
                        }
 
514
                        
 
515
                        ActionRoutine (Catalog.GetString ("Task Uncompleted"),
 
516
                                       Catalog.GetString ("The selected task has been marked as \"incomplete\"."),
 
517
                                       taskId, listId);
 
518
                }
 
519
    }
 
520
}