OSDN Git Service

- Correct issue with importing when not a premium member.
[neighbornote/NeighborNote.git] / src / cx / fbn / nevernote / threads / SyncRunner.java
1 /*\r
2  * This file is part of NixNote \r
3  * Copyright 2009 Randy Baumgarte\r
4  * \r
5  * This file may be licensed under the terms of of the\r
6  * GNU General Public License Version 2 (the ``GPL'').\r
7  *\r
8  * Software distributed under the License is distributed\r
9  * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either\r
10  * express or implied. See the GPL for the specific language\r
11  * governing rights and limitations.\r
12  *\r
13  * You should have received a copy of the GPL along with this\r
14  * program. If not, go to http://www.gnu.org/licenses/gpl.html\r
15  * or write to the Free Software Foundation, Inc.,\r
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r
17  *\r
18 */\r
19 package cx.fbn.nevernote.threads;\r
20 \r
21 import java.io.BufferedOutputStream;\r
22 import java.io.File;\r
23 import java.io.FileOutputStream;\r
24 import java.io.IOException;\r
25 import java.io.InputStream;\r
26 import java.io.UnsupportedEncodingException;\r
27 import java.net.UnknownHostException;\r
28 import java.util.ArrayList;\r
29 import java.util.Calendar;\r
30 import java.util.Date;\r
31 import java.util.GregorianCalendar;\r
32 import java.util.HashMap;\r
33 import java.util.List;\r
34 import java.util.TreeSet;\r
35 import java.util.Vector;\r
36 import java.util.concurrent.LinkedBlockingQueue;\r
37 \r
38 import org.apache.http.HttpEntity;\r
39 import org.apache.http.HttpResponse;\r
40 import org.apache.http.NameValuePair;\r
41 import org.apache.http.client.ClientProtocolException;\r
42 import org.apache.http.client.HttpClient;\r
43 import org.apache.http.client.entity.UrlEncodedFormEntity;\r
44 import org.apache.http.client.methods.HttpPost;\r
45 import org.apache.http.impl.client.DefaultHttpClient;\r
46 import org.apache.http.message.BasicNameValuePair;\r
47 import org.apache.http.protocol.HTTP;\r
48 import org.apache.thrift.TException;\r
49 import org.apache.thrift.protocol.TBinaryProtocol;\r
50 import org.apache.thrift.transport.THttpClient;\r
51 import org.apache.thrift.transport.TTransportException;\r
52 \r
53 import com.evernote.edam.error.EDAMNotFoundException;\r
54 import com.evernote.edam.error.EDAMSystemException;\r
55 import com.evernote.edam.error.EDAMUserException;\r
56 import com.evernote.edam.notestore.NoteStore;\r
57 import com.evernote.edam.notestore.NoteStore.Client;\r
58 import com.evernote.edam.notestore.SyncChunk;\r
59 import com.evernote.edam.notestore.SyncState;\r
60 import com.evernote.edam.type.Data;\r
61 import com.evernote.edam.type.LinkedNotebook;\r
62 import com.evernote.edam.type.Note;\r
63 import com.evernote.edam.type.Notebook;\r
64 import com.evernote.edam.type.Resource;\r
65 import com.evernote.edam.type.SavedSearch;\r
66 import com.evernote.edam.type.SharedNotebook;\r
67 import com.evernote.edam.type.Tag;\r
68 import com.evernote.edam.type.User;\r
69 import com.evernote.edam.userstore.AuthenticationResult;\r
70 import com.evernote.edam.userstore.UserStore;\r
71 import com.trolltech.qt.core.QByteArray;\r
72 import com.trolltech.qt.core.QFile;\r
73 import com.trolltech.qt.core.QIODevice.OpenModeFlag;\r
74 import com.trolltech.qt.core.QObject;\r
75 import com.trolltech.qt.core.QTextCodec;\r
76 import com.trolltech.qt.gui.QMessageBox;\r
77 \r
78 import cx.fbn.nevernote.signals.NoteIndexSignal;\r
79 import cx.fbn.nevernote.signals.NoteResourceSignal;\r
80 import cx.fbn.nevernote.signals.NoteSignal;\r
81 import cx.fbn.nevernote.signals.NotebookSignal;\r
82 import cx.fbn.nevernote.signals.SavedSearchSignal;\r
83 import cx.fbn.nevernote.signals.StatusSignal;\r
84 import cx.fbn.nevernote.signals.SyncSignal;\r
85 import cx.fbn.nevernote.signals.TagSignal;\r
86 import cx.fbn.nevernote.sql.DatabaseConnection;\r
87 import cx.fbn.nevernote.sql.DeletedItemRecord;\r
88 import cx.fbn.nevernote.utilities.ApplicationLogger;\r
89 \r
90 public class SyncRunner extends QObject implements Runnable {\r
91         \r
92         private final ApplicationLogger logger;\r
93                 private DatabaseConnection              conn;\r
94                 private boolean                                 idle;\r
95                 public boolean                                  error;\r
96                 public volatile Vector<String>  errorSharedNotebooks;\r
97                 public volatile HashMap<String,String>  errorSharedNotebooksIgnored;\r
98                 public volatile boolean                 isConnected;\r
99                 public volatile boolean                 keepRunning;\r
100                 public volatile String                  authToken;\r
101                 private long                                    evernoteUpdateCount;\r
102                 private final String userAgent = "NixNote/" + System.getProperty("os.name")\r
103                                                                 +"/"+System.getProperty("java.vendor") + "/"\r
104                                                                 + System.getProperty("java.version") +";";\r
105                 \r
106                 public volatile NoteStore.Client                localNoteStore;\r
107                 private UserStore.Client                                userStore;\r
108                 \r
109                 public volatile StatusSignal                    status;\r
110                 public volatile TagSignal                               tagSignal;\r
111                 public volatile NotebookSignal                  notebookSignal;\r
112                 public volatile NoteIndexSignal                 noteIndexSignal;\r
113                 public volatile NoteSignal                              noteSignal;\r
114                 public volatile SavedSearchSignal               searchSignal;\r
115                 public volatile NoteResourceSignal              resourceSignal;\r
116                 public volatile SyncSignal                              syncSignal;\r
117                 public volatile boolean                                 authRefreshNeeded;\r
118                 public volatile boolean                                 syncNeeded;\r
119                 public volatile boolean                                 disableUploads;\r
120                 public volatile boolean                                 syncDeletedContent;\r
121                 private volatile Vector<String>                 dirtyNoteGuids;\r
122                 \r
123             public volatile String username = ""; \r
124             public volatile String password = ""; \r
125                 public volatile String userStoreUrl;\r
126 //          private final static String consumerKey = "baumgarte"; \r
127 //          private final static String consumerSecret = "eb8b5740e17cb55f";\r
128             public String noteStoreUrlBase;\r
129             private THttpClient userStoreTrans;\r
130             private TBinaryProtocol userStoreProt;\r
131             //private AuthenticationResult authResult;\r
132             private AuthenticationResult linkedAuthResult;\r
133             private User user; \r
134 //          private long authTimeRemaining;\r
135             public long authRefreshTime;\r
136             public long failedRefreshes = 0;\r
137             public  THttpClient noteStoreTrans;\r
138             public TBinaryProtocol noteStoreProt;\r
139             public String noteStoreUrl;\r
140             public long sequenceDate;\r
141             public int updateSequenceNumber;\r
142             private boolean refreshNeeded;\r
143             private volatile LinkedBlockingQueue<String> workQueue;\r
144                 private static int MAX_QUEUED_WAITING = 1000;\r
145                 String dbuid;\r
146                 String dburl;\r
147                 String indexUrl;\r
148                 String resourceUrl;\r
149                 String dbpswd;\r
150                 String dbcpswd;\r
151                 private final TreeSet<String> ignoreTags;\r
152                 private final TreeSet<String> ignoreNotebooks;\r
153                 private final TreeSet<String> ignoreLinkedNotebooks;\r
154                 private HashMap<String,String> badTagSync;\r
155         \r
156                 \r
157                 \r
158         public SyncRunner(String logname, String u, String i, String r, String uid, String pswd, String cpswd) {\r
159                 logger = new ApplicationLogger(logname);\r
160                 \r
161                 noteSignal = new NoteSignal();\r
162                 status = new StatusSignal();\r
163                 tagSignal = new TagSignal();\r
164                 notebookSignal = new NotebookSignal();\r
165                 noteIndexSignal = new NoteIndexSignal();\r
166                 noteSignal = new NoteSignal();\r
167                 searchSignal = new SavedSearchSignal();\r
168                 syncSignal = new SyncSignal();\r
169                 resourceSignal = new NoteResourceSignal();\r
170                 resourceUrl = r;\r
171                 indexUrl = i;\r
172                 dbuid = uid;\r
173                 dburl = u;\r
174                 dbpswd = pswd;\r
175                 dbcpswd = cpswd;\r
176 //              this.setAutoDelete(false);\r
177                 \r
178                 isConnected = false;\r
179                 syncNeeded = false;\r
180                 authRefreshNeeded = false;\r
181                 keepRunning = true;\r
182                 idle = true;\r
183                 disableUploads = false;\r
184                 ignoreTags = new TreeSet<String>();\r
185                 ignoreNotebooks = new TreeSet<String>();\r
186                 ignoreLinkedNotebooks = new TreeSet<String>();\r
187                 \r
188 //              setAutoDelete(false);\r
189                 workQueue=new LinkedBlockingQueue<String>(MAX_QUEUED_WAITING);\r
190         }\r
191         @Override\r
192         public void run() {\r
193                 errorSharedNotebooks = new Vector<String>();\r
194                 errorSharedNotebooksIgnored = new HashMap<String,String>();\r
195                 try {\r
196                         logger.log(logger.EXTREME, "Starting thread");\r
197                         conn = new DatabaseConnection(logger, dburl, indexUrl, resourceUrl, dbuid, dbpswd, dbcpswd, 200);\r
198                         while(keepRunning) {\r
199                                 logger.log(logger.EXTREME, "Blocking until work is found");\r
200                                 String work = workQueue.take();\r
201                                 logger.log(logger.LOW, "Dirty Notes Before Sync: " +new Integer(conn.getNoteTable().getDirtyCount()).toString());\r
202                                 logger.log(logger.EXTREME, "Work found: " +work);\r
203                                 if (work.equalsIgnoreCase("stop")) {\r
204                                         idle=false;\r
205                                         return;\r
206                                 }\r
207                                 idle=false;\r
208                                 error=false;\r
209                                 if (syncNeeded) {\r
210                                         logger.log(logger.EXTREME, "SyncNeeded is true");\r
211                                         refreshNeeded=false;\r
212                                         sequenceDate = conn.getSyncTable().getLastSequenceDate();\r
213                                         updateSequenceNumber = conn.getSyncTable().getUpdateSequenceNumber();\r
214                                         try {\r
215                                                 logger.log(logger.EXTREME, "Beginning sync");\r
216                                                 evernoteSync(localNoteStore);\r
217                                                 logger.log(logger.EXTREME, "Sync finished");\r
218                                         } catch (UnknownHostException e) {\r
219                                                 status.message.emit(e.getMessage());\r
220                                         }\r
221                                 }\r
222                                 idle=true;\r
223                                 logger.log(logger.EXTREME, "Signaling refresh finished.  refreshNeeded=" +refreshNeeded);\r
224                                 syncSignal.finished.emit(refreshNeeded);\r
225                                 if (error) {\r
226                                         syncSignal.errorDisconnect.emit();\r
227                                         status.message.emit(tr("Error synchronizing - see log for details."));\r
228                                 }\r
229                                 logger.log(logger.LOW, "Dirty Notes After Sync: " +new Integer(conn.getNoteTable().getDirtyCount()).toString());\r
230                         }\r
231                 }       \r
232                 catch (InterruptedException e1) {\r
233                         e1.printStackTrace();\r
234                 }\r
235                 conn.dbShutdown();\r
236         }\r
237 \r
238         \r
239         public DatabaseConnection getConnection() {\r
240                 return conn;\r
241         }\r
242 \r
243         public boolean isIdle() {\r
244                 return idle;\r
245         }\r
246 \r
247 \r
248         public void setConnected(boolean c) {\r
249                 isConnected = c;\r
250         }\r
251         public void setKeepRunning(boolean r) {\r
252                 logger.log(logger.EXTREME, "Setting keepRunning=" +r);\r
253                 keepRunning = r;\r
254         }\r
255         public void setNoteStore(NoteStore.Client c) {\r
256                 logger.log(logger.EXTREME, "Setting NoteStore in sync thread");\r
257                 localNoteStore = c;\r
258         }\r
259         public void setUserStore(UserStore.Client c) {\r
260                 logger.log(logger.EXTREME, "Setting UserStore in sync thread");\r
261                 userStore = c;\r
262         }\r
263 \r
264         public void setEvernoteUpdateCount(long s) {\r
265                 logger.log(logger.EXTREME, "Setting Update Count in sync thread");\r
266                 evernoteUpdateCount = s;\r
267         }\r
268         \r
269         //***************************************************************\r
270     //***************************************************************\r
271     //** These functions deal with Evernote communications\r
272     //***************************************************************\r
273     //***************************************************************\r
274         // Synchronize changes with Evernote\r
275         @SuppressWarnings("unused")\r
276         private void evernoteSync(Client noteStore) throws java.net.UnknownHostException {\r
277                 logger.log(logger.HIGH, "Entering SyncRunner.evernoteSync");\r
278                 \r
279                 // Rebuild list of tags & notebooks to ignore\r
280                 ignoreNotebooks.clear();\r
281                 List<String> ignore = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");\r
282                 for (int i=0; i<ignore.size(); i++) \r
283                         ignoreNotebooks.add(ignore.get(i));\r
284                 \r
285                 ignore.clear();\r
286                 ignore = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");\r
287                 for (int i=0; i<ignore.size(); i++) \r
288                         ignoreLinkedNotebooks.add(ignore.get(i));\r
289                 \r
290                 ignoreTags.clear();\r
291                 ignore = conn.getSyncTable().getIgnoreRecords("TAG");\r
292                 for (int i=0; i<ignore.size(); i++) \r
293                         ignoreTags.add(ignore.get(i));\r
294 \r
295                 // Make sure we are connected & should keep running\r
296                 if (isConnected && keepRunning) {\r
297                         error = false;\r
298                         logger.log(logger.EXTREME, "Synchronizing with Evernote");\r
299                         status.message.emit(tr("Synchronizing with Evernote"));\r
300                         \r
301                         // Get user information\r
302                         try {\r
303                                 logger.log(logger.EXTREME, "getting user from userstore");\r
304                                 User user = userStore.getUser(authToken);\r
305                                 logger.log(logger.EXTREME, "Saving user information");\r
306                                 syncSignal.saveUserInformation.emit(user);\r
307                         } catch (EDAMUserException e1) {\r
308                                 e1.printStackTrace();\r
309                                 status.message.emit(tr("User exception getting user account information.  Aborting sync and disconnecting"));\r
310                                 syncSignal.errorDisconnect.emit();\r
311                                 error = true;\r
312                                 enDisconnect();\r
313                                 return;\r
314                         } catch (EDAMSystemException e1) {\r
315                                 e1.printStackTrace();\r
316                                 status.message.emit(tr("System error user account information.  Aborting sync and disconnecting!"));\r
317                                 syncSignal.errorDisconnect.emit();\r
318                                 error = true;\r
319                                 enDisconnect();\r
320                                 return;\r
321                         } catch (TException e1) {\r
322                                 e1.printStackTrace();\r
323                                 syncSignal.errorDisconnect.emit();\r
324                                 error = true;\r
325                                 status.message.emit(tr("Transaction error getting user account information.  Aborting sync and disconnecting!"));\r
326                                 enDisconnect();\r
327                                 return;\r
328                         }\r
329                         \r
330                         // Get sync state\r
331                         SyncState syncState = null;\r
332                         try {   \r
333                                 logger.log(logger.EXTREME, "Getting sync state");\r
334                                 syncState = noteStore.getSyncState(authToken);  \r
335                                 syncSignal.saveUploadAmount.emit(syncState.getUploaded());\r
336                                 syncSignal.saveEvernoteUpdateCount.emit(syncState.getUpdateCount());\r
337                                 evernoteUpdateCount = syncState.getUpdateCount();\r
338                         } catch (EDAMUserException e) {\r
339                                 e.printStackTrace();\r
340                                 status.message.emit(tr("Error getting sync state! Aborting sync and disconnecting!"));\r
341                                 syncSignal.errorDisconnect.emit();\r
342                                 enDisconnect();\r
343                                 return;\r
344                         } catch (EDAMSystemException e) {\r
345                                 e.printStackTrace();\r
346                                 status.message.emit(tr("Error getting sync state! Aborting sync and disconnecting!"));\r
347                                 syncSignal.errorDisconnect.emit();\r
348                                 enDisconnect();\r
349                                 return;\r
350                         } catch (TException e) {\r
351                                 e.printStackTrace();\r
352                                 status.message.emit(tr("Error getting sync state! Aborting sync and disconnecting!"));\r
353                                 syncSignal.errorDisconnect.emit();\r
354                                 enDisconnect();\r
355                                 return;\r
356                         }\r
357                         \r
358                         if (syncState == null) {\r
359                                 logger.log(logger.EXTREME, "Sync State is null");\r
360                                 status.message.emit(tr("Syncronization Error!"));\r
361                                 return;\r
362                         }\r
363 \r
364                         // Determine what to do. \r
365                         // If we need to do a full sync.\r
366                         logger.log(logger.LOW, "Full Sequence Before: " +syncState.getFullSyncBefore());\r
367                         logger.log(logger.LOW, "Last Sequence Date: " +sequenceDate);\r
368                         logger.log(logger.LOW, "Var Last Sequence Number: " +updateSequenceNumber);\r
369                         logger.log(logger.LOW, "DB Last Sequence Number: " + conn.getSyncTable().getUpdateSequenceNumber());\r
370                         if (syncState.getFullSyncBefore() > sequenceDate) {\r
371                                 logger.log(logger.EXTREME, "Full sequence date has expired");\r
372                                 sequenceDate = 0;\r
373                                 conn.getSyncTable().setLastSequenceDate(0);\r
374                                 updateSequenceNumber = 0;\r
375                                 conn.getSyncTable().setUpdateSequenceNumber(0);\r
376                         }\r
377                         // Check for "special" sync instructions\r
378                         String syncLinked = conn.getSyncTable().getRecord("FullLinkedNotebookSync");\r
379                         String syncShared = conn.getSyncTable().getRecord("FullSharedNotebookSync");\r
380                         String syncNotebooks = conn.getSyncTable().getRecord("FullNotebookSync");\r
381                         String syncInkNoteImages = conn.getSyncTable().getRecord("FullInkNoteImageSync");\r
382                         if (syncLinked != null) {\r
383                                 downloadAllLinkedNotebooks(localNoteStore);\r
384                         }\r
385                         if (syncShared != null) {\r
386                                 downloadAllSharedNotebooks(localNoteStore);\r
387                         }\r
388                         if (syncNotebooks != null) {\r
389                                 downloadAllNotebooks(localNoteStore);\r
390                         }\r
391                         \r
392                         if (syncInkNoteImages != null) {\r
393                                 List<String> guids = conn.getNoteTable().noteResourceTable.findInkNotes();\r
394                                 for (int i=0; i<guids.size(); i++) {\r
395                                         downloadInkNoteImage(guids.get(i), authToken);\r
396                                 }\r
397                                 conn.getSyncTable().deleteRecord("FullInkNoteImageSync");\r
398                         }\r
399                         \r
400                         // If there are remote changes\r
401                         logger.log(logger.LOW, "Update Count: " +syncState.getUpdateCount());\r
402                         logger.log(logger.LOW, "Last Update Count: " +updateSequenceNumber);\r
403                         \r
404                         if (syncState.getUpdateCount() > updateSequenceNumber) {\r
405                                 logger.log(logger.EXTREME, "Refresh needed is true");\r
406                                 refreshNeeded = true;\r
407                                 logger.log(logger.EXTREME, "Downloading changes");\r
408                                 syncRemoteToLocal(localNoteStore);\r
409                         }\r
410                         \r
411                         //*****************************************\r
412                         //* Sync linked/shared notebooks \r
413                         //*****************************************\r
414                         syncLinkedNotebooks();\r
415                         \r
416                         if (!disableUploads) {\r
417                                 logger.log(logger.EXTREME, "Uploading changes");\r
418                                 // Synchronize remote changes\r
419                                 if (!error)\r
420                                         syncExpunged(localNoteStore);\r
421                                 if (!error)\r
422                                         syncLocalTags(localNoteStore);\r
423                                 if (!error)\r
424                                         syncLocalNotebooks(localNoteStore);\r
425                                 if (!error)\r
426                                         syncLocalLinkedNotebooks(localNoteStore);\r
427                                 if (!error) \r
428                                         syncDeletedNotes(localNoteStore);\r
429                                 if (!error)\r
430                                         syncLocalNotes();\r
431                                 if (!error)\r
432                                         syncLocalSavedSearches(localNoteStore);\r
433                         }\r
434                         \r
435                         status.message.emit(tr("Cleaning up"));\r
436                         List<String> notes = conn.getNoteTable().expungeIgnoreSynchronizedNotes(conn.getSyncTable().getIgnoreRecords("NOTEBOOK"), \r
437                                         conn.getSyncTable().getIgnoreRecords("TAG"), conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK"));\r
438                         if (notes.size() > 0)\r
439                                 syncSignal.refreshLists.emit();\r
440                         \r
441                         //*****************************************\r
442                         //* End of synchronization\r
443                         //*****************************************\r
444                         if (refreshNeeded)\r
445                                 syncSignal.refreshLists.emit();\r
446                         \r
447                         if (!error) {\r
448                                 logger.log(logger.LOW, "Sync completed.  Errors=" +error);\r
449                                 if (!disableUploads) \r
450                                         status.message.emit(tr("Synchronizing complete"));\r
451                                 else\r
452                                         status.message.emit(tr("Download syncronization complete.  Uploads have been disabled."));\r
453                                 \r
454                                 logger.log(logger.EXTREME, "Saving sync time");\r
455                                 if (syncState.getCurrentTime() > sequenceDate)\r
456                                         sequenceDate = syncState.getCurrentTime();\r
457                                 if (syncState.getUpdateCount() > updateSequenceNumber)\r
458                                         updateSequenceNumber = syncState.getUpdateCount();\r
459                                 conn.getSyncTable().setLastSequenceDate(sequenceDate);\r
460                                 conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
461                         }\r
462                 }\r
463                 logger.log(logger.HIGH, "Leaving SyncRunner.evernoteSync");\r
464         }\r
465         \r
466         // Sync deleted items with Evernote\r
467         private void syncExpunged(Client noteStore) {\r
468                 logger.log(logger.HIGH, "Entering SyncRunner.syncExpunged");\r
469                 \r
470                 List<DeletedItemRecord> expunged = conn.getDeletedTable().getAllDeleted();\r
471                 boolean error = false;\r
472                 for (int i=0; i<expunged.size() && keepRunning; i++) {\r
473 \r
474 //                      if (authRefreshNeeded)\r
475 //                              if (!refreshConnection())\r
476 //                                      return;\r
477 \r
478                         try {\r
479                                 if (expunged.get(i).type.equalsIgnoreCase("TAG")) {\r
480                                         logger.log(logger.EXTREME, "Tag expunged");\r
481                                         updateSequenceNumber = noteStore.expungeTag(authToken, expunged.get(i).guid);\r
482                                         conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
483                                         conn.getSyncTable().setLastSequenceDate(sequenceDate);\r
484                                         conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
485                                         conn.getDeletedTable().expungeDeletedItem(expunged.get(i).guid, "TAG");                                 \r
486                                 }\r
487                                 if      (expunged.get(i).type.equalsIgnoreCase("NOTEBOOK")) {\r
488                                         logger.log(logger.EXTREME, "Notebook expunged");\r
489                                         updateSequenceNumber = noteStore.expungeNotebook(authToken, expunged.get(i).guid);\r
490                                         conn.getSyncTable().setLastSequenceDate(sequenceDate);\r
491                                         conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
492                                         conn.getDeletedTable().expungeDeletedItem(expunged.get(i).guid, "NOTEBOOK");\r
493                                 }\r
494                                 if (expunged.get(i).type.equalsIgnoreCase("NOTE")) {\r
495                                         logger.log(logger.EXTREME, "Note expunged");\r
496                                         updateSequenceNumber = noteStore.deleteNote(authToken, expunged.get(i).guid);\r
497                                         refreshNeeded = true;\r
498                                         conn.getSyncTable().setLastSequenceDate(sequenceDate);\r
499                                         conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
500                                         conn.getDeletedTable().expungeDeletedItem(expunged.get(i).guid, "NOTE");\r
501                                 }\r
502                                 if (expunged.get(i).type.equalsIgnoreCase("SAVEDSEARCH")) {\r
503                                         logger.log(logger.EXTREME, "saved search expunged");\r
504                                         updateSequenceNumber = noteStore.expungeSearch(authToken, expunged.get(i).guid);\r
505                                         conn.getSyncTable().setLastSequenceDate(sequenceDate);\r
506                                         conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
507                                         conn.getDeletedTable().expungeDeletedItem(expunged.get(i).guid, "SAVEDSEARCH");\r
508                                 }\r
509                         } catch (EDAMUserException e) {\r
510                                 logger.log(logger.LOW, "EDAM User Excepton in syncExpunged: " +expunged.get(i).guid);   // This can happen if we try to delete a deleted note\r
511                         } catch (EDAMSystemException e) {\r
512                                 logger.log(logger.LOW, "EDAM System Excepton in syncExpunged: "+expunged.get(i).guid);\r
513                                 logger.log(logger.LOW, e.getStackTrace());\r
514                                 error=true;\r
515                         } catch (EDAMNotFoundException e) {\r
516                                 logger.log(logger.LOW, "EDAM Not Found Excepton in syncExpunged: "+expunged.get(i).guid);\r
517                         } catch (TException e) {\r
518                                 logger.log(logger.LOW, "EDAM TExcepton in syncExpunged: "+expunged.get(i).guid);\r
519                                 logger.log(logger.LOW, e.getStackTrace());\r
520                                 error=true;\r
521                         }\r
522                 }\r
523                 if (!error)\r
524                         conn.getDeletedTable().expungeAllDeletedRecords();\r
525                 \r
526                 logger.log(logger.HIGH, "Leaving SyncRunner.syncExpunged");\r
527 \r
528         }\r
529         private void syncDeletedNotes(Client noteStore) {\r
530                 if (syncDeletedContent)\r
531                         return;\r
532                 logger.log(logger.HIGH, "Entering SyncRunner.syncDeletedNotes");\r
533                 status.message.emit(tr("Synchronizing deleted notes."));\r
534 \r
535                 List<Note> notes = conn.getNoteTable().getDirty();\r
536                 // Sync the local notebooks with Evernote's\r
537                 for (int i=0; i<notes.size() && keepRunning; i++) {\r
538                         \r
539 //                      if (authRefreshNeeded)\r
540 //                              if (!refreshConnection())\r
541 //                                      return;\r
542                         \r
543                         Note enNote = notes.get(i);\r
544                         try {\r
545                                 if (enNote.getUpdateSequenceNum() > 0 && (enNote.isActive() == false || enNote.getDeleted() > 0)) {\r
546                                         if (syncDeletedContent) {\r
547                                                 logger.log(logger.EXTREME, "Deleted note found & synch content selected");\r
548                                                 Note delNote = conn.getNoteTable().getNote(enNote.getGuid(), true, true, true, true, true);\r
549                                                 delNote = getNoteContent(delNote);\r
550                                                 delNote = noteStore.updateNote(authToken, delNote);\r
551                                                 enNote.setUpdateSequenceNum(delNote.getUpdateSequenceNum());\r
552                                                 conn.getNoteTable().updateNoteSequence(enNote.getGuid(), enNote.getUpdateSequenceNum());\r
553                                         } else {\r
554                                                 logger.log(logger.EXTREME, "Deleted note found & sync content not selected");\r
555                                                 int usn = noteStore.deleteNote(authToken, enNote.getGuid());\r
556                                                 enNote.setUpdateSequenceNum(usn);\r
557                                                 conn.getNoteTable().updateNoteSequence(enNote.getGuid(), enNote.getUpdateSequenceNum());                                                \r
558                                         }\r
559                                         logger.log(logger.EXTREME, "Resetting deleted dirty flag");\r
560                                         conn.getNoteTable().resetDirtyFlag(enNote.getGuid());\r
561                                         updateSequenceNumber = enNote.getUpdateSequenceNum();\r
562                                         logger.log(logger.EXTREME, "Saving sequence number");\r
563                                         conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
564                                 }                               \r
565                         } catch (EDAMUserException e) {\r
566                                 //logger.log(logger.LOW, "*** EDAM User Excepton syncLocalNotes "+e);\r
567                                 //status.message.emit("Error sending local note: " +e.getParameter());\r
568                                 //logger.log(logger.LOW, e.toString()); \r
569                                 //error = true;\r
570                         } catch (EDAMSystemException e) {\r
571                                 logger.log(logger.LOW, "*** EDAM System Excepton syncLocalNotes "+e);\r
572                                 status.message.emit(tr("Error: ") +e);\r
573                                 logger.log(logger.LOW, e.toString());           \r
574                                 error = true;\r
575                         } catch (EDAMNotFoundException e) {\r
576                                 //logger.log(logger.LOW, "*** EDAM Not Found Excepton syncLocalNotes " +e);\r
577                                 //status.message.emit("Error deleting local note: " +e +" - Continuing");\r
578                                 //logger.log(logger.LOW, e.toString());         \r
579                                 //error = true;\r
580                         } catch (TException e) {\r
581                                 logger.log(logger.LOW, "*** EDAM TExcepton syncLocalNotes "+e);\r
582                                 status.message.emit(tr("Error sending local note: ") +e);\r
583                                 logger.log(logger.LOW, e.toString());   \r
584                                 error = true;\r
585                         }               \r
586                 }\r
587         }\r
588         // Sync notes with Evernote\r
589         private void syncLocalNotes() {\r
590                 logger.log(logger.HIGH, "Entering SyncRunner.syncNotes");\r
591                 logger.log(logger.LOW, "Dirty local notes found: " +new Integer(conn.getNoteTable().getDirtyCount()).toString());\r
592                 status.message.emit(tr("Sending local notes."));\r
593 \r
594                 List<Note> notes = conn.getNoteTable().getDirty();\r
595                 // Sync the local notebooks with Evernote's\r
596                 for (int i=0; i<notes.size() && keepRunning; i++) {\r
597                         syncLocalNote(localNoteStore, notes.get(i), authToken);\r
598                 }\r
599                 logger.log(logger.HIGH, "Leaving SyncRunner.syncNotes");\r
600 \r
601         }\r
602         // Sync notes with Evernote\r
603         private void syncLocalNote(Client noteStore, Note enNote, String token) {\r
604                 logger.log(logger.HIGH, "Entering SyncRunner.syncNotes");\r
605                 status.message.emit(tr("Sending local notes."));\r
606                         \r
607                 if (enNote.isActive()) {\r
608                         try {\r
609                                 if (enNote.getUpdateSequenceNum() > 0) {\r
610                                         logger.log(logger.EXTREME, "Active dirty note found - non new - " +enNote.getGuid());\r
611                                         logger.log(logger.EXTREME, "Fetching note content");\r
612                                         enNote = getNoteContent(enNote);\r
613                                         logger.log(logger.MEDIUM, "Updating note : "+ enNote.getGuid() +" <title>" +enNote.getTitle()+"</title>");\r
614                                         enNote = noteStore.updateNote(token, enNote);\r
615                                 } else { \r
616                                         logger.log(logger.EXTREME, "Active dirty found - new note " +enNote.getGuid());\r
617                                         String oldGuid = enNote.getGuid();\r
618                                         logger.log(logger.MEDIUM, "Fetching note content");\r
619                                         enNote = getNoteContent(enNote);\r
620                                         logger.log(logger.MEDIUM, "Creating note : "+ enNote.getGuid() +" <title>" +enNote.getTitle()+"</title>");\r
621                                         enNote = noteStore.createNote(token, enNote);\r
622                                         logger.log(logger.MEDIUM, "New note Guid : "+ enNote.getGuid() +" <title>" +enNote.getTitle()+"</title>");\r
623                                         noteSignal.guidChanged.emit(oldGuid, enNote.getGuid());\r
624                                         conn.getNoteTable().updateNoteGuid(oldGuid, enNote.getGuid());\r
625                                 }\r
626                                 updateSequenceNumber = enNote.getUpdateSequenceNum();\r
627                                 logger.log(logger.EXTREME, "Saving note");\r
628                                 conn.getNoteTable().updateNoteSequence(enNote.getGuid(), enNote.getUpdateSequenceNum());\r
629                                 List<Resource> rl = enNote.getResources();\r
630                                 logger.log(logger.EXTREME, "Getting note resources");\r
631                                 for (int j=0; j<enNote.getResourcesSize() && keepRunning; j++) {\r
632                                         Resource newRes = rl.get(j);\r
633                                         Data d = newRes.getData();\r
634                                         if (d!=null) {  \r
635                                                 logger.log(logger.EXTREME, "Calculating resource hash");\r
636                                                 String hash = byteArrayToHexString(d.getBodyHash());\r
637                                                 logger.log(logger.EXTREME, "updating resources by hash");\r
638                                                 String oldGuid = conn.getNoteTable().noteResourceTable.getNoteResourceGuidByHashHex(enNote.getGuid(), hash);\r
639                                                 conn.getNoteTable().updateNoteResourceGuidbyHash(enNote.getGuid(), newRes.getGuid(), hash);\r
640                                                 resourceSignal.resourceGuidChanged.emit(enNote.getGuid(), oldGuid, newRes.getGuid());\r
641                                         }\r
642                                 }\r
643                                 logger.log(logger.EXTREME, "Resetting note dirty flag");\r
644                                 conn.getNoteTable().resetDirtyFlag(enNote.getGuid());\r
645                                 updateSequenceNumber = enNote.getUpdateSequenceNum();\r
646                                 logger.log(logger.EXTREME, "Emitting note sequence number change");\r
647                                 conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
648 \r
649                         } catch (EDAMUserException e) {\r
650                                 logger.log(logger.LOW, "*** EDAM User Excepton syncLocalNotes "+e);\r
651                                 status.message.emit(tr("Error sending local note: ")     +e.getParameter());\r
652                                 logger.log(logger.LOW, e.toString());   \r
653                                 error = true;\r
654                         } catch (EDAMSystemException e) {\r
655                                 logger.log(logger.LOW, "*** EDAM System Excepton syncLocalNotes "+e);\r
656                                 status.message.emit(tr("Error: ") +e);\r
657                                 logger.log(logger.LOW, e.toString());           \r
658                                 error = true;\r
659                         } catch (EDAMNotFoundException e) {\r
660                                 logger.log(logger.LOW, "*** EDAM Not Found Excepton syncLocalNotes " +e);\r
661                                 status.message.emit(tr("Error sending local note: ") +e);\r
662                                 logger.log(logger.LOW, e.toString());   \r
663                                 error = true;\r
664                         } catch (TException e) {\r
665                                 logger.log(logger.LOW, "*** EDAM TExcepton syncLocalNotes "+e);\r
666                                 status.message.emit(tr("Error sending local note: ") +e);\r
667                                 logger.log(logger.LOW, e.toString());   \r
668                                 error = true;\r
669                         }\r
670                 }\r
671                 logger.log(logger.HIGH, "Leaving SyncRunner.syncLocalNote");\r
672 \r
673         }\r
674 \r
675         // Sync Notebooks with Evernote\r
676         private void syncLocalNotebooks(Client noteStore) {\r
677                 logger.log(logger.HIGH, "Entering SyncRunner.syncLocalNotebooks");\r
678                 \r
679                 status.message.emit(tr("Sending local notebooks."));\r
680                 List<Notebook> remoteList = new ArrayList<Notebook>();\r
681                 try {\r
682                         logger.log(logger.EXTREME, "Getting remote notebooks to compare with local");\r
683                         remoteList = noteStore.listNotebooks(authToken);\r
684                 } catch (EDAMUserException e1) {\r
685                         logger.log(logger.LOW, "*** EDAM User Excepton syncLocalNotebooks getting remote Notebook List");\r
686                         status.message.emit(tr("Error: ") +e1);\r
687                         logger.log(logger.LOW, e1.toString());          \r
688                         error = true;\r
689                 } catch (EDAMSystemException e1) {\r
690                         logger.log(logger.LOW, "*** EDAM System Excepton syncLocalNotebooks getting remote Notebook List");\r
691                         status.message.emit(tr("Error: ") +e1);\r
692                         logger.log(logger.LOW, e1.toString());  \r
693                         error = true;\r
694                 } catch (TException e1) {\r
695                         logger.log(logger.LOW, "*** EDAM Transaction Excepton syncLocalNotebooks getting remote Notebook List");\r
696                         status.message.emit(tr("Error: ") +e1);\r
697                         logger.log(logger.LOW, e1.toString());  \r
698                         error = true;\r
699                 }\r
700                 logger.log(logger.EXTREME, "Getting local dirty notebooks");\r
701                 List<Notebook> notebooks = conn.getNotebookTable().getDirty();\r
702                 int sequence;\r
703                 // Sync the local notebooks with Evernote's\r
704                 for (int i=0; i<notebooks.size() && keepRunning; i++) {\r
705                         \r
706 //                      if (authRefreshNeeded)\r
707 //                              if (!refreshConnection())\r
708 //                                      return;\r
709                         \r
710                         Notebook enNotebook = notebooks.get(i);\r
711                         try {\r
712                                 if (enNotebook.getUpdateSequenceNum() > 0) {\r
713                                         logger.log(logger.EXTREME, "Existing notebook is dirty");\r
714                                         sequence = noteStore.updateNotebook(authToken, enNotebook);\r
715                                 } else {\r
716                                         logger.log(logger.EXTREME, "New dirty notebook found");\r
717                                         String oldGuid = enNotebook.getGuid();\r
718                                         boolean found = false;\r
719                                         \r
720                                         // Look for a notebook with the same name.  If one is found, we don't need \r
721                                         // to create another one\r
722                                         logger.log(logger.EXTREME, "Looking for matching notebook name");\r
723                                         for (int k=0; k<remoteList.size() && !found && keepRunning; k++) {\r
724                                                 if (remoteList.get(k).getName().equalsIgnoreCase(enNotebook.getName())) {\r
725                                                         enNotebook = remoteList.get(k);\r
726                                                         logger.log(logger.EXTREME, "Matching notebook found");\r
727                                                         found = true;\r
728                                                 }\r
729                                         }\r
730                                         if (!found)\r
731                                                 enNotebook = noteStore.createNotebook(authToken, enNotebook);\r
732                                         \r
733                                         logger.log(logger.EXTREME, "Updating notebook in database");\r
734                                         conn.getNotebookTable().updateNotebookGuid(oldGuid, enNotebook.getGuid());\r
735                                         sequence = enNotebook.getUpdateSequenceNum();\r
736                                 }\r
737                                 logger.log(logger.EXTREME, "Updating notebook sequence in database");\r
738                                 conn.getNotebookTable().updateNotebookSequence(enNotebook.getGuid(), sequence);\r
739                                 logger.log(logger.EXTREME, "Resetting dirty flag in notebook");\r
740                                 conn.getNotebookTable().resetDirtyFlag(enNotebook.getGuid());\r
741                                 updateSequenceNumber = sequence;\r
742                                 logger.log(logger.EXTREME, "Emitting sequence number to main thread");\r
743                                 conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
744                         } catch (EDAMUserException e) {\r
745                                 logger.log(logger.LOW, "*** EDAM User Excepton syncLocalNotebooks");\r
746                                 logger.log(logger.LOW, e.toString());   \r
747                                 error = true;\r
748                         } catch (EDAMSystemException e) {\r
749                                 logger.log(logger.LOW, "*** EDAM System Excepton syncLocalNotebooks");\r
750                                 logger.log(logger.LOW, e.toString());           \r
751                                 error = true;\r
752                         } catch (EDAMNotFoundException e) {\r
753                                 logger.log(logger.LOW, "*** EDAM Not Found Excepton syncLocalNotebooks");\r
754                                 logger.log(logger.LOW, e.toString());           \r
755                                 error = true;\r
756                         } catch (TException e) {\r
757                                 logger.log(logger.LOW, "*** EDAM TExcepton syncLocalNotebooks");\r
758                                 logger.log(logger.LOW, e.toString());   \r
759                                 error = true;\r
760                         }               \r
761                 }\r
762                 logger.log(logger.HIGH, "Leaving SyncRunner.syncLocalNotebooks");\r
763 \r
764         }\r
765         // Sync Tags with Evernote\r
766         private void syncLocalTags(Client noteStore) {\r
767                 logger.log(logger.HIGH, "Entering SyncRunner.syncLocalTags");\r
768                 List<Tag> remoteList = new ArrayList<Tag>();\r
769                 status.message.emit(tr("Sending local tags."));\r
770                 \r
771                 try {\r
772                         logger.log(logger.EXTREME, "Getting remote tags to compare names with the local tags");\r
773                         remoteList = noteStore.listTags(authToken);\r
774                 } catch (EDAMUserException e1) {\r
775                         logger.log(logger.LOW, "*** EDAM User Excepton syncLocalTags getting remote Tag List");\r
776                         status.message.emit(tr("Error: ") +e1);\r
777                         logger.log(logger.LOW, e1.toString());  \r
778                         error = true;\r
779                 } catch (EDAMSystemException e1) {\r
780                         logger.log(logger.LOW, "*** EDAM System Excepton syncLocalTags getting remote Tag List");\r
781                         status.message.emit(tr("Error: ") +e1);\r
782                         logger.log(logger.LOW, e1.toString());          \r
783                         error = true;\r
784                 } catch (TException e1) {\r
785                         logger.log(logger.LOW, "*** EDAM Transaction Excepton syncLocalTags getting remote Tag List");\r
786                         status.message.emit(tr("Error: ") +e1);\r
787                         logger.log(logger.LOW, e1.toString());  \r
788                         error = true;\r
789                 }               \r
790                 \r
791                 int sequence;\r
792                 \r
793                 if (badTagSync == null)\r
794                         badTagSync = new HashMap<String,String>();\r
795                 else\r
796                         badTagSync.clear();\r
797                 \r
798                 Tag enTag = findNextTag();\r
799                 \r
800                 // This is a hack.  Sometimes this function goes flookey and goes into a \r
801                 // perpetual loop.  This causes  NeverNote to flood Evernote's servers.\r
802                 // This is a safety valve to prevent unlimited loops.\r
803                 int maxCount = conn.getTagTable().getDirty().size()+10;\r
804                 int loopCount = 0;\r
805                 \r
806                 while(enTag!=null && loopCount < maxCount) {\r
807                         loopCount++;\r
808 //                      if (authRefreshNeeded)\r
809 //                              if (!refreshConnection())\r
810 //                                      return;\r
811 \r
812                         try {\r
813                                 if (enTag.getUpdateSequenceNum() > 0) {\r
814                                         logger.log(logger.EXTREME, "Updating tag");\r
815                                         sequence = noteStore.updateTag(authToken, enTag);\r
816                                 } else {\r
817                                         \r
818                                         // Look for a tag with the same name.  If one is found, we don't need \r
819                                         // to create another one\r
820                                         logger.log(logger.EXTREME, "New tag.  Comparing with remote names");\r
821                                         boolean found = false;\r
822                                         String oldGuid = enTag.getGuid();\r
823                                         for (int k=0; k<remoteList.size() && !found && keepRunning; k++) {\r
824                                                 if (remoteList.get(k).getName().equalsIgnoreCase(enTag.getName())) {\r
825                                                         conn.getTagTable().updateTagGuid(enTag.getGuid(), remoteList.get(k).getGuid());\r
826                                                         enTag = remoteList.get(k);\r
827                                                         logger.log(logger.EXTREME, "Matching tag name found");\r
828                                                         found = true;\r
829                                                 }\r
830                                         }\r
831                                         if (!found)\r
832                                                 enTag = noteStore.createTag(authToken, enTag);\r
833                                         else\r
834                                                 enTag.setUpdateSequenceNum(noteStore.updateTag(authToken,enTag));\r
835                                         sequence = enTag.getUpdateSequenceNum();\r
836                                         if (!oldGuid.equals(enTag.getGuid())) {\r
837                                                 logger.log(logger.EXTREME, "Updating tag guid");\r
838                                                 conn.getTagTable().updateTagGuid(oldGuid, enTag.getGuid());\r
839                                         }\r
840                                 }\r
841                                 logger.log(logger.EXTREME, "Updating tag sequence number");\r
842                                 conn.getTagTable().updateTagSequence(enTag.getGuid(), sequence);\r
843                                 logger.log(logger.EXTREME, "Resetting tag dirty flag");\r
844                                 conn.getTagTable().resetDirtyFlag(enTag.getGuid());\r
845                                 logger.log(logger.EXTREME, "Emitting sequence number to the main thread.");\r
846                                 updateSequenceNumber = sequence;\r
847                                 conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
848                         } catch (EDAMUserException e) {\r
849                                 logger.log(logger.LOW, "*** EDAM User Excepton syncLocalTags: " +enTag.getName());\r
850                                 logger.log(logger.LOW, e.toString());\r
851                                 badTagSync.put(enTag.getGuid(),null);\r
852                                 error = true;\r
853                         } catch (EDAMSystemException e) {\r
854                                 logger.log(logger.LOW, "** EDAM System Excepton syncLocalTags: " +enTag.getName());\r
855                                 logger.log(logger.LOW, e.toString());   \r
856                                 badTagSync.put(enTag.getGuid(),null);\r
857                                 error = true;\r
858                         } catch (EDAMNotFoundException e) {\r
859                                 logger.log(logger.LOW, "*** EDAM Not Found Excepton syncLocalTags: " +enTag.getName());\r
860                                 logger.log(logger.LOW, e.toString());\r
861                                 badTagSync.put(enTag.getGuid(),null);\r
862                                 error = true;\r
863                         } catch (TException e) {\r
864                                 logger.log(logger.LOW, "*** EDAM TExcepton syncLocalTags: " +enTag.getName());\r
865                                 logger.log(logger.LOW, e.toString());\r
866                                 badTagSync.put(enTag.getGuid(),null);\r
867                                 error = true;\r
868                         }       \r
869                         \r
870                         // Find the next tag\r
871                         logger.log(logger.EXTREME, "Finding next tag");\r
872                         enTag = findNextTag();\r
873                 }\r
874                 logger.log(logger.HIGH, "Leaving SyncRunner.syncLocalTags");\r
875         }\r
876         private void syncLocalLinkedNotebooks(Client noteStore) {\r
877                 logger.log(logger.HIGH, "Entering SyncRunner.syncLocalLinkedNotebooks");\r
878                 \r
879                 List<String> list = conn.getLinkedNotebookTable().getDirtyGuids();\r
880                 for (int i=0; i<list.size(); i++) {\r
881                         LinkedNotebook book = conn.getLinkedNotebookTable().getNotebook(list.get(i));\r
882                         try {\r
883                                 noteStore.updateLinkedNotebook(authToken, book);\r
884                         } catch (EDAMUserException e) {\r
885                                 logger.log(logger.LOW, "*** EDAM User Excepton syncLocalLinkedNotebooks");\r
886                                 status.message.emit(tr("Error: ") +e);\r
887                                 logger.log(logger.LOW, e.toString());           \r
888                                 error = true;\r
889                                 e.printStackTrace();\r
890                         } catch (EDAMNotFoundException e) {\r
891                                 logger.log(logger.LOW, "*** EDAM Not Found Excepton syncLocalLinkedNotebooks");\r
892                                 status.message.emit(tr("Error: ") +e);\r
893                                 logger.log(logger.LOW, e.toString());           \r
894                                 error = true;\r
895                                 e.printStackTrace();\r
896                         } catch (EDAMSystemException e) {\r
897                                 logger.log(logger.LOW, "*** EDAM System Excepton syncLocalLinkedNotebooks");\r
898                                 status.message.emit(tr("Error: ") +e);\r
899                                 logger.log(logger.LOW, e.toString());           \r
900                                 error = true;\r
901                                 e.printStackTrace();\r
902                         } catch (TException e) {\r
903                                 logger.log(logger.LOW, "*** EDAM TExcepton syncLocalLinkedNotebooks");\r
904                                 status.message.emit(tr("Error: ") +e);\r
905                                 logger.log(logger.LOW, e.toString());           \r
906                                 error = true;\r
907                                 e.printStackTrace();\r
908                         }\r
909                 }\r
910                 logger.log(logger.HIGH, "Leaving SyncRunner.syncLocalLinkedNotebooks");\r
911         }\r
912         // Sync Saved Searches with Evernote\r
913         private void syncLocalSavedSearches(Client noteStore) {\r
914                 logger.log(logger.HIGH, "Entering SyncRunner.syncLocalSavedSearches");\r
915                 List<SavedSearch> remoteList = new ArrayList<SavedSearch>();\r
916                 status.message.emit(tr("Sending saved searches."));\r
917         \r
918                 logger.log(logger.EXTREME, "Getting saved searches to compare with local");\r
919                 try {\r
920                         remoteList = noteStore.listSearches(authToken);\r
921                 } catch (EDAMUserException e1) {\r
922                         logger.log(logger.LOW, "*** EDAM User Excepton syncLocalTags getting remote saved search List");\r
923                         status.message.emit(tr("Error: ") +e1);\r
924                         logger.log(logger.LOW, e1.toString());  \r
925                         error = true;\r
926                 } catch (EDAMSystemException e1) {\r
927                         logger.log(logger.LOW, "*** EDAM System Excepton syncLocalTags getting remote saved search List");\r
928                         status.message.emit(tr("Error: ") +e1);\r
929                         logger.log(logger.LOW, e1.toString());          \r
930                         error = true;\r
931                 } catch (TException e1) {\r
932                         logger.log(logger.LOW, "*** EDAM Transaction Excepton syncLocalTags getting remote saved search List");\r
933                         status.message.emit(tr("Error: ") +e1);\r
934                         logger.log(logger.LOW, e1.toString());  \r
935                         error = true;\r
936                 }               \r
937                 \r
938                 List<SavedSearch> searches = conn.getSavedSearchTable().getDirty();\r
939                 int sequence;\r
940                 // Sync the local notebooks with Evernote's\r
941                 logger.log(logger.EXTREME, "Beginning to send saved searches");\r
942                 for (int i=0; i<searches.size() &&  keepRunning; i++) {\r
943                         \r
944 //                      if (authRefreshNeeded)\r
945 //                              if (!refreshConnection())\r
946 //                                      return;\r
947                         \r
948                         SavedSearch enSearch = searches.get(i);\r
949                         try {\r
950                                 if (enSearch.getUpdateSequenceNum() > 0) \r
951                                         sequence = noteStore.updateSearch(authToken, enSearch);\r
952                                 else {\r
953                                         logger.log(logger.EXTREME, "New saved search found.");\r
954                                         // Look for a tag with the same name.  If one is found, we don't need \r
955                                         // to create another one\r
956                                         boolean found = false;\r
957                                         logger.log(logger.EXTREME, "Matching remote saved search names with local");\r
958                                         for (int k=0; k<remoteList.size() && !found && keepRunning; k++) {\r
959                                                 if (remoteList.get(k).getName().equalsIgnoreCase(enSearch.getName())) {\r
960                                                         enSearch = remoteList.get(k);\r
961                                                         found = true;\r
962                                                         logger.log(logger.EXTREME, "Matching saved search found");\r
963                                                         sequence = enSearch.getUpdateSequenceNum();\r
964                                                 }\r
965                                         }\r
966 \r
967                                         String oldGuid = enSearch.getGuid();\r
968                                         if (!found)\r
969                                                 enSearch = noteStore.createSearch(authToken, enSearch);\r
970                                         sequence = enSearch.getUpdateSequenceNum();\r
971                                         logger.log(logger.EXTREME, "Updating tag guid in local database");\r
972                                         conn.getSavedSearchTable().updateSavedSearchGuid(oldGuid, enSearch.getGuid());\r
973                                 }\r
974                                 logger.log(logger.EXTREME, "Updating tag sequence in local database");\r
975                                 conn.getSavedSearchTable().updateSavedSearchSequence(enSearch.getGuid(), sequence);\r
976                                 logger.log(logger.EXTREME, "Resetting tag dirty flag");\r
977                                 conn.getSavedSearchTable().resetDirtyFlag(enSearch.getGuid());\r
978                                 logger.log(logger.EXTREME, "Emitting sequence number to the main thread.");\r
979                                 updateSequenceNumber = sequence;\r
980                                 conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
981                         } catch (EDAMUserException e) {\r
982                                 logger.log(logger.LOW, "*** EDAM User Excepton syncLocalTags");\r
983                                 logger.log(logger.LOW, e.toString());   \r
984                                 error = true;\r
985                         } catch (EDAMSystemException e) {\r
986                                 logger.log(logger.LOW, "** EDAM System Excepton syncLocalTags");\r
987                                 logger.log(logger.LOW, e.toString());   \r
988                                 error = true;\r
989                         } catch (EDAMNotFoundException e) {\r
990                                 logger.log(logger.LOW, "*** EDAM Not Found Excepton syncLocalTags");\r
991                                 logger.log(logger.LOW, e.toString());   \r
992                                 error = true;\r
993                         } catch (TException e) {\r
994                                 logger.log(logger.LOW, "*** EDAM TExcepton syncLocalTags");\r
995                                 logger.log(logger.LOW, e.toString());   \r
996                                 error = true;\r
997                         }               \r
998                 }\r
999 \r
1000                 logger.log(logger.HIGH, "Entering SyncRunner.syncLocalSavedSearches");\r
1001         }       \r
1002 \r
1003         // Sync evernote changes with local database\r
1004         private void syncRemoteToLocal(Client noteStore) {\r
1005                 logger.log(logger.HIGH, "Entering SyncRunner.syncRemoteToLocal");\r
1006 \r
1007                 List<Note> dirtyNotes = conn.getNoteTable().getDirty();\r
1008                 dirtyNoteGuids = new Vector<String>();\r
1009                 for (int i=0; i<dirtyNotes.size() && keepRunning; i++) {\r
1010                         dirtyNoteGuids.add(dirtyNotes.get(i).getGuid());\r
1011                 }\r
1012                 \r
1013                 int chunkSize = 10;\r
1014                 SyncChunk chunk = null;\r
1015                 boolean fullSync = false;\r
1016                 boolean more = true;\r
1017                 \r
1018                 if (updateSequenceNumber == 0)\r
1019                         fullSync = true;\r
1020                 \r
1021                 status.message.emit(tr("Downloading 0% complete."));\r
1022                 \r
1023                 while(more &&  keepRunning) {\r
1024                         \r
1025 //                      if (authRefreshNeeded)\r
1026 //                              if (!refreshConnection())\r
1027 //                                      return;\r
1028                         \r
1029                         int sequence = updateSequenceNumber;\r
1030                         try {\r
1031 //                              conn.beginTransaction();\r
1032                                 logger.log(logger.EXTREME, "Getting chunk from Evernote");\r
1033                                 chunk = noteStore.getSyncChunk(authToken, sequence, chunkSize, fullSync);\r
1034                                 logger.log(logger.LOW, "Chunk High Sequence: " +chunk.getChunkHighUSN());\r
1035                         } catch (EDAMUserException e) {\r
1036                                 error = true;\r
1037                                 e.printStackTrace();\r
1038                                 status.message.emit(e.getMessage());\r
1039                         } catch (EDAMSystemException e) {\r
1040                                 error = true;\r
1041                                 e.printStackTrace();\r
1042                                 status.message.emit(e.getMessage());\r
1043                         } catch (TException e) {\r
1044                                 error = true;\r
1045                                 e.printStackTrace();\r
1046                                 status.message.emit(e.getMessage());\r
1047                         } \r
1048                         if (error || chunk == null) \r
1049                                 return;\r
1050                                 \r
1051                 \r
1052                         \r
1053                         syncRemoteTags(chunk.getTags());\r
1054                         syncRemoteSavedSearches(chunk.getSearches());\r
1055                         syncRemoteNotebooks(chunk.getNotebooks());\r
1056                         syncRemoteNotes(noteStore, chunk.getNotes(), fullSync, authToken);\r
1057                         syncRemoteResources(noteStore, chunk.getResources());\r
1058                         syncRemoteLinkedNotebooks(chunk.getLinkedNotebooks());\r
1059                         \r
1060                         // Signal about any updated notes to invalidate the cache\r
1061                         for (int i=0; i<chunk.getNotesSize(); i++) \r
1062                                 noteSignal.noteChanged.emit(chunk.getNotes().get(i).getGuid(), null); \r
1063                         syncExpungedNotes(chunk);\r
1064                         \r
1065                         \r
1066                         // Check for more notes\r
1067                         if (chunk.getChunkHighUSN() <= updateSequenceNumber) \r
1068                                 more = false;\r
1069                         if (error)\r
1070                                 more = false;\r
1071                         logger.log(logger.EXTREME, "More notes? " +more);\r
1072 \r
1073                         \r
1074                         // Save the chunk sequence number\r
1075                         if (!error && chunk.getChunkHighUSN() > 0 && keepRunning) {\r
1076                                 logger.log(logger.EXTREME, "emitting sequence number to main thread");\r
1077                                 updateSequenceNumber = chunk.getChunkHighUSN();\r
1078                                 conn.getSyncTable().setLastSequenceDate(chunk.getCurrentTime());\r
1079                                 conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
1080 //                              conn.commitTransaction();\r
1081                         }\r
1082                         \r
1083                         \r
1084                         if (more) {\r
1085                                 long pct = chunk.getChunkHighUSN() * 100;\r
1086                                 conn.getSyncTable().setLastSequenceDate(chunk.getCurrentTime());\r
1087                                 pct = pct/evernoteUpdateCount;\r
1088                                 status.message.emit(tr("Downloading ") +new Long(pct).toString()+tr("% complete."));\r
1089                         }\r
1090 //                      conn.commitTransaction();\r
1091                 }\r
1092                 logger.log(logger.HIGH, "Leaving SyncRunner.syncRemoteToLocal");\r
1093         }\r
1094         // Sync expunged notes\r
1095         private void syncExpungedNotes(SyncChunk chunk) {\r
1096                 // Do the local deletes\r
1097                 logger.log(logger.EXTREME, "Doing local deletes");\r
1098                 List<String> guid = chunk.getExpungedNotes();\r
1099                 if (guid != null) {\r
1100                         for (int i=0; i<guid.size() && keepRunning; i++) {\r
1101                                 String notebookGuid = "";\r
1102                                 Note localNote = conn.getNoteTable().getNote(guid.get(i), false, false, false, false, false);\r
1103                                 if (localNote != null) {\r
1104                                         conn.getNoteTable().updateNoteSequence(guid.get(i), 0);\r
1105                                         notebookGuid = localNote.getNotebookGuid();\r
1106                                 }\r
1107                                 if (!conn.getNotebookTable().isNotebookLocal(notebookGuid)) {\r
1108                                         logger.log(logger.EXTREME, "Expunging local note from database");\r
1109                                         conn.getNoteTable().expungeNote(guid.get(i), true, false);\r
1110                                 }\r
1111                         }\r
1112                 }\r
1113                 guid = chunk.getExpungedNotebooks();\r
1114                 if (guid != null)\r
1115                         for (int i=0; i<guid.size() && keepRunning; i++) {\r
1116                                 logger.log(logger.EXTREME, "Expunging local notebook from database");\r
1117                                 conn.getNotebookTable().expungeNotebook(guid.get(i), false);\r
1118                         }\r
1119                 guid = chunk.getExpungedTags();\r
1120                 if (guid != null)\r
1121                         for (int i=0; i<guid.size() && keepRunning; i++) {\r
1122                                 logger.log(logger.EXTREME, "Expunging tags from local database");\r
1123                                 conn.getTagTable().expungeTag(guid.get(i), false);\r
1124                         }\r
1125                 guid = chunk.getExpungedSearches();\r
1126                 if (guid != null) \r
1127                         for (int i=0; i<guid.size() && keepRunning; i++) {\r
1128                                 logger.log(logger.EXTREME, "Expunging saved search from local database");\r
1129                                 conn.getSavedSearchTable().expungeSavedSearch(guid.get(i), false);\r
1130                         }\r
1131                 guid = chunk.getExpungedLinkedNotebooks();\r
1132                 if (guid != null) \r
1133                         for (int i=0; i<guid.size() && keepRunning; i++) {\r
1134                                 logger.log(logger.EXTREME, "Expunging linked notebook from local database");\r
1135                                 conn.getLinkedNotebookTable().expungeNotebook(guid.get(i), false);\r
1136                         }\r
1137 \r
1138         }\r
1139         // Sync remote tags\r
1140         private void syncRemoteTags(List<Tag> tags) {\r
1141                 logger.log(logger.EXTREME, "Entering SyncRunner.syncRemoteTags");\r
1142                 if (tags != null) {\r
1143                         for (int i=0; i<tags.size() && keepRunning; i++) {\r
1144                                 String oldGuid;\r
1145                                 oldGuid = conn.getTagTable().findTagByName(tags.get(i).getName());\r
1146                                 if (oldGuid != null && !tags.get(i).getGuid().equalsIgnoreCase(oldGuid))\r
1147                                         conn.getTagTable().updateTagGuid(oldGuid, tags.get(i).getGuid());\r
1148                                 conn.getTagTable().syncTag(tags.get(i), false);\r
1149                         }\r
1150                 }\r
1151                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncRemoteTags");\r
1152         }\r
1153         // Sync remote saved searches\r
1154         private void syncRemoteSavedSearches(List<SavedSearch> searches) {\r
1155                 logger.log(logger.EXTREME, "Entering SyncRunner.syncSavedSearches");\r
1156                 if (searches != null) {\r
1157                         for (int i=0; i<searches.size() && keepRunning; i++) {\r
1158                                 String oldGuid;\r
1159                                 oldGuid = conn.getSavedSearchTable().findSavedSearchByName(searches.get(i).getName());\r
1160                                 if (oldGuid != null && !searches.get(i).getGuid().equalsIgnoreCase(oldGuid))\r
1161                                         conn.getSavedSearchTable().updateSavedSearchGuid(oldGuid, searches.get(i).getGuid());\r
1162                                 conn.getSavedSearchTable().syncSavedSearch(searches.get(i), false);\r
1163                         }\r
1164                 }\r
1165                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncSavedSearches");\r
1166         }\r
1167         // Sync remote linked notebooks\r
1168         private void syncRemoteLinkedNotebooks(List<LinkedNotebook> books) {\r
1169                 logger.log(logger.EXTREME, "Entering SyncRunner.syncLinkedNotebooks");\r
1170                 if (books != null) {\r
1171                         for (int i=0; i<books.size() && keepRunning; i++) {\r
1172                                 conn.getLinkedNotebookTable().updateNotebook(books.get(i), false); \r
1173                         }\r
1174                 }\r
1175                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncLinkedNotebooks");\r
1176         }\r
1177         // Sync remote Notebooks 2\r
1178         private void syncRemoteNotebooks(List<Notebook> notebooks) {\r
1179                 logger.log(logger.EXTREME, "Entering SyncRunner.syncRemoteNotebooks");\r
1180                 if (notebooks != null) {\r
1181                         for (int i=0; i<notebooks.size() && keepRunning; i++) {\r
1182                                 String oldGuid;\r
1183                                 oldGuid = conn.getNotebookTable().findNotebookByName(notebooks.get(i).getName());\r
1184                                 if (oldGuid != null && !conn.getNotebookTable().isNotebookLocal(oldGuid) && !notebooks.get(i).getGuid().equalsIgnoreCase(oldGuid))\r
1185                                         conn.getNotebookTable().updateNotebookGuid(oldGuid, notebooks.get(i).getGuid());\r
1186                                 conn.getNotebookTable().syncNotebook(notebooks.get(i), false); \r
1187                                 \r
1188                                 // Synchronize shared notebook information\r
1189 //                              if (notebooks.get(i).getSharedNotebookIdsSize() > 0) {\r
1190 //                                      conn.getSharedNotebookTable().expungeNotebookByGuid(notebooks.get(i).getGuid(), false);\r
1191 //                                      for (int j=0; j<notebooks.get(i).getSharedNotebookIdsSize(); j++) {\r
1192 //                                              syncRemoteSharedNotebook(notebooks.get(i).getGuid(), notebooks.get(i).getSharedNotebookIds().get(j), authToken);\r
1193 //                                      }\r
1194 //                              }\r
1195                         }\r
1196                 }                       \r
1197                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncRemoteNotebooks");\r
1198         }\r
1199         // Sync remote shared notebook\r
1200 //      private void syncRemoteSharedNotebook(String guid, Long id, String token) {\r
1201 //              List<SharedNotebook> books = noteStore.getSharedNotebookByAuth(authToken);\r
1202 //      }\r
1203         // Sync remote Resources\r
1204         private void syncRemoteResources(Client noteStore, List<Resource> resource) {\r
1205                 logger.log(logger.EXTREME, "Entering SyncRunner.syncRemoteResources");\r
1206                 if (resource != null) {\r
1207                         for (int i=0; i<resource.size() && keepRunning; i++) {\r
1208                                 syncRemoteResource(noteStore, resource.get(i), authToken);\r
1209                         }\r
1210                 }\r
1211                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncRemoteResources");\r
1212         }\r
1213         // Sync remote resource\r
1214         private void syncRemoteResource(Client noteStore, Resource resource, String authToken) {\r
1215                 // This is how the logic for this works.\r
1216                 // 1.) If the resource is not in the local database, we add it.\r
1217                 // 2.) If a copy of the resource is in the local database and the note isn't dirty, we update the local copy\r
1218                 // 3.) If a copy of the resource is in the local databbase and it is dirty and the hash doesn't match, we ignore it because there\r
1219                 //     is a conflict.  The note conflict should get a copy of the resource at that time.\r
1220                 \r
1221                 Note n = conn.getNoteTable().getNote(resource.getNoteGuid(), false, false, false, false, false);\r
1222                 if (n!=null) {\r
1223                         logger.log(logger.HIGH, "Resource for note " +n.getGuid() +" : " +n.getTitle());\r
1224                 }\r
1225                 boolean saveNeeded = false;\r
1226                 /* #1 */                Resource r = getEvernoteResource(noteStore, resource.getGuid(), true,true,true, authToken);\r
1227                                                 Resource l = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), false);\r
1228                                                 if (l == null) {\r
1229                                                         logger.log(logger.HIGH, "Local resource not found");\r
1230                                                         saveNeeded = true;\r
1231                                                 } else {\r
1232                 /* #2 */                        boolean isNoteDirty = conn.getNoteTable().isNoteDirty(r.getNoteGuid());\r
1233                                                         if (!isNoteDirty) {\r
1234                                                                 logger.log(logger.HIGH, "Local resource found, but is not dirty");\r
1235                                                                 saveNeeded = true;\r
1236                                                         } else {\r
1237                 /* #3 */                                String remoteHash = "";\r
1238                                                                 if (r != null && r.getData() != null && r.getData().getBodyHash() != null)\r
1239                                                                         remoteHash = byteArrayToHexString(r.getData().getBodyHash());\r
1240                                                                 String localHash = "";\r
1241                                                                 if (l != null && l.getData() != null && l.getData().getBodyHash() != null)\r
1242                                                                         remoteHash = byteArrayToHexString(l.getData().getBodyHash());\r
1243                                                 \r
1244                                                                 if (localHash.equalsIgnoreCase(remoteHash))\r
1245                                                                         saveNeeded = true;\r
1246                                                         }\r
1247                                                 }\r
1248                                                 \r
1249                                                 logger.log(logger.HIGH, "Resource save needed: " +saveNeeded);\r
1250                                                 if (saveNeeded) \r
1251                                                         conn.getNoteTable().noteResourceTable.updateNoteResource(r, false);\r
1252                                                 if (r.getMime().equalsIgnoreCase("application/vnd.evernote.ink"))\r
1253                                                         downloadInkNoteImage(r.getGuid(), authToken);\r
1254                 \r
1255 \r
1256         }\r
1257         // Sync remote notes\r
1258         private void syncRemoteNotes(Client noteStore, List<Note> note, boolean fullSync, String token) {\r
1259                 logger.log(logger.EXTREME, "Entering SyncRunner.syncRemoteNotes");\r
1260                 if (note != null) {\r
1261                         for (int i=0; i<note.size() && keepRunning; i++) {\r
1262                                 Note n = getEvernoteNote(noteStore, note.get(i).getGuid(), true, fullSync, true,true, token);\r
1263                                 syncRemoteNote(n, fullSync, token);\r
1264                         }\r
1265                 }\r
1266                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncRemoteNotes");\r
1267         }\r
1268         private void syncRemoteNote(Note n, boolean fullSync, String token) {\r
1269                 if (n!=null) {\r
1270                         \r
1271                         // Basically, this is how the sync logic for a note works.\r
1272                         // If the remote note has changed and the local has not, we\r
1273                         // accept the change.\r
1274                         // If both the local & remote have changed but the sequence\r
1275                         // numbers are the same, we don't accept the change.  This\r
1276                         // seems to happen when attachments are indexed by the server.\r
1277                         // If both the local & remote have changed and the sequence numbers\r
1278                         // are different we move the local copy to a local notebook (making sure\r
1279                         // to copy all resources) and we accept the new one.                    \r
1280                         boolean conflictingNote = true;\r
1281                         logger.log(logger.EXTREME, "Checking for duplicate note " +n.getGuid());\r
1282                         if (dirtyNoteGuids != null && dirtyNoteGuids.contains(n.getGuid())) { \r
1283                                 logger.log(logger.EXTREME, "Conflict check beginning");\r
1284                                 conflictingNote = checkForConflict(n);\r
1285                                 logger.log(logger.EXTREME, "Conflict check results " +conflictingNote);\r
1286                                 if (conflictingNote)\r
1287                                         moveConflictingNote(n.getGuid());\r
1288                         }\r
1289                         boolean ignoreNote = false;\r
1290                         if (ignoreNotebooks.contains(n.getNotebookGuid()))\r
1291                                 ignoreNote = true;\r
1292                         for (int i=0; i<n.getTagGuidsSize(); i++) {\r
1293                                 if (ignoreTags.contains(n.getTagGuids().get(i))) {\r
1294                                         ignoreNote = true;\r
1295                                         i=n.getTagGuidsSize();\r
1296                                 }\r
1297                         }\r
1298                                 \r
1299                         if ((conflictingNote || fullSync) && !ignoreNote) {\r
1300                                 logger.log(logger.EXTREME, "Saving Note");\r
1301                                 conn.getNoteTable().syncNote(n);\r
1302                                 // The following was commented out because it caused a race condition on the database where resources \r
1303                                 // may be lost.  We do the same thing elsewhere;.\r
1304 //                              noteSignal.noteChanged.emit(n.getGuid(), null);   // Signal to ivalidate note cache \r
1305                                 noteSignal.noteDownloaded.emit(n, true);                // Signal to add note to index\r
1306                                         logger.log(logger.EXTREME, "Note Saved");\r
1307                                 if (fullSync && n.getResources() != null) {\r
1308                                         for (int q=0; q<n.getResources().size() && keepRunning; q++) {\r
1309                                                 logger.log(logger.EXTREME, "Getting note resources.");\r
1310                                                 conn.getNoteTable().noteResourceTable.updateNoteResource(n.getResources().get(q), false);\r
1311                                                 if (n.getResources().get(q).getMime().equalsIgnoreCase("application/vnd.evernote.ink"))\r
1312                                                         downloadInkNoteImage(n.getResources().get(q).getGuid(), token);\r
1313                                         }\r
1314                                 }\r
1315                         }\r
1316                 }\r
1317         }\r
1318         private Note getEvernoteNote(Client noteStore, String guid, boolean withContent, boolean withResourceData, boolean withResourceRecognition, boolean withResourceAlternateData, String token) { \r
1319                 Note n = null;\r
1320                 try {\r
1321                         logger.log(logger.EXTREME, "Retrieving note " +guid);\r
1322                         n = noteStore.getNote(token, guid, withContent, withResourceData, withResourceRecognition, withResourceAlternateData);\r
1323                         logger.log(logger.EXTREME, "Note " +guid +" has been retrieved.");\r
1324                 } catch (EDAMUserException e) {\r
1325                         logger.log(logger.LOW, "*** EDAM User Excepton getEvernoteNote");\r
1326                         logger.log(logger.LOW, e.toString());   \r
1327                         error = true;\r
1328                         e.printStackTrace();\r
1329                 } catch (EDAMSystemException e) {\r
1330                         logger.log(logger.LOW, "*** EDAM System Excepton getEvernoteNote");\r
1331                         logger.log(logger.LOW, e.toString());   \r
1332                         error = true;\r
1333                         e.printStackTrace();\r
1334                 } catch (EDAMNotFoundException e) {\r
1335                         logger.log(logger.LOW, "*** EDAM Not Found Excepton getEvernoteNote");\r
1336                         logger.log(logger.LOW, e.toString());   \r
1337                         error = true;\r
1338                         e.printStackTrace();\r
1339                 } catch (TException e) {\r
1340                         logger.log(logger.LOW, "*** EDAM TExcepton getEvernoteNote");\r
1341                         logger.log(logger.LOW, e.toString());   \r
1342                         error = true;\r
1343                         e.printStackTrace();\r
1344                 }\r
1345                 return n;\r
1346         }\r
1347         private Resource getEvernoteResource(Client noteStore, String guid, boolean withData, boolean withRecognition, boolean withAttributes, String token) { \r
1348                 Resource n = null;\r
1349                 try {\r
1350                         logger.log(logger.EXTREME, "Retrieving resource " +guid);\r
1351                         n = noteStore.getResource(token, guid, withData, withRecognition, withAttributes, withAttributes);\r
1352                         logger.log(logger.EXTREME, "Resource " +guid +" has been retrieved.");\r
1353                 } catch (EDAMUserException e) {\r
1354                         logger.log(logger.LOW, "*** EDAM User Excepton getEvernoteNote");\r
1355                         logger.log(logger.LOW, e.toString());   \r
1356                         error = true;\r
1357                         e.printStackTrace();\r
1358                 } catch (EDAMSystemException e) {\r
1359                         logger.log(logger.LOW, "*** EDAM System Excepton getEvernoteNote");\r
1360                         logger.log(logger.LOW, e.toString());   \r
1361                         error = true;\r
1362                         e.printStackTrace();\r
1363                 } catch (EDAMNotFoundException e) {\r
1364                         logger.log(logger.LOW, "*** EDAM Not Found Excepton getEvernoteNote");\r
1365                         logger.log(logger.LOW, e.toString());   \r
1366                         error = true;\r
1367                         e.printStackTrace();\r
1368                 } catch (TException e) {\r
1369                         logger.log(logger.LOW, "*** EDAM TExcepton getEvernoteNote");\r
1370                         logger.log(logger.LOW, e.toString());   \r
1371                         error = true;\r
1372                         e.printStackTrace();\r
1373                 }\r
1374                 return n;\r
1375         }\r
1376 \r
1377         \r
1378         private boolean checkForConflict(Note n) {\r
1379                 logger.log(logger.EXTREME, "Checking note sequence number  " +n.getGuid());\r
1380                 Note oldNote = conn.getNoteTable().getNote(n.getGuid(), false, false, false, false, false);\r
1381                 logger.log(logger.EXTREME, "Local/Remote sequence numbers: " +oldNote.getUpdateSequenceNum()+"/"+n.getUpdateSequenceNum());\r
1382                 if (oldNote.getUpdateSequenceNum() == n.getUpdateSequenceNum())\r
1383                         return false;\r
1384                 return true;\r
1385         }\r
1386         \r
1387         private void moveConflictingNote(String guid) {\r
1388                 logger.log(logger.EXTREME, "Conflicting change found for note " +guid);\r
1389                 List<Notebook> books = conn.getNotebookTable().getAllLocal();\r
1390                 String notebookGuid = null;\r
1391                 for (int i=0; i<books.size() && keepRunning; i++) {\r
1392                         if (books.get(i).getName().equalsIgnoreCase("Conflicting Changes (local)") ||\r
1393                                         books.get(i).getName().equalsIgnoreCase("Conflicting Changes")) {\r
1394                                 notebookGuid = books.get(i).getGuid();\r
1395                                 i=books.size();\r
1396                         }\r
1397                 }\r
1398                 \r
1399                 if (notebookGuid == null) {\r
1400                         logger.log(logger.EXTREME, "Building conflicting change notebook " +guid);\r
1401                         Calendar currentTime = new GregorianCalendar();\r
1402                         Long l = new Long(currentTime.getTimeInMillis());\r
1403                         long prevTime = l;\r
1404                         while (prevTime==l) {\r
1405                                 currentTime = new GregorianCalendar();\r
1406                                 l=currentTime.getTimeInMillis();\r
1407                         }\r
1408                         String randint = new String(Long.toString(l));\r
1409                 \r
1410                         Notebook newBook = new Notebook();\r
1411                         newBook.setUpdateSequenceNum(0);\r
1412                         newBook.setGuid(randint);\r
1413                         newBook.setName("Conflicting Changes");\r
1414                         newBook.setServiceCreated(new Date().getTime());\r
1415                         newBook.setServiceUpdated(new Date().getTime());\r
1416                         newBook.setDefaultNotebook(false);\r
1417                         newBook.setPublished(false);\r
1418                         \r
1419                         conn.getNotebookTable().addNotebook(newBook, false, true);\r
1420                         notebookSignal.listChanged.emit();\r
1421                         notebookGuid = newBook.getGuid();\r
1422                         refreshNeeded = true;\r
1423                 }\r
1424                 \r
1425                 // Now that we have a good notebook guid, we need to move the conflicting note\r
1426                 // to the local notebook\r
1427                 logger.log(logger.EXTREME, "Moving conflicting note " +guid);\r
1428                 Calendar currentTime = new GregorianCalendar();\r
1429                 Long l = new Long(currentTime.getTimeInMillis());\r
1430                 long prevTime = l;\r
1431                 while (prevTime==l) {\r
1432                         currentTime = new GregorianCalendar();\r
1433                         l = currentTime.getTimeInMillis();\r
1434                 }\r
1435                 String newGuid = new String(Long.toString(l));\r
1436                                         \r
1437                 Note oldNote = conn.getNoteTable().getNote(guid, true, true, false, false, false);\r
1438                 for (int i=0; i<oldNote.getResources().size() && keepRunning; i++) {\r
1439                         l = new Long(currentTime.getTimeInMillis());\r
1440                         String newResG = new String(Long.toString(l));\r
1441                         String oldResG = oldNote.getResources().get(i).getGuid();\r
1442                         conn.getNoteTable().noteResourceTable.resetUpdateSequenceNumber(oldResG, true);\r
1443                         conn.getNoteTable().noteResourceTable.updateNoteResourceGuid(oldResG, newResG, true);\r
1444                 }\r
1445                 \r
1446                 conn.getNoteTable().resetNoteSequence(guid);\r
1447                 conn.getNoteTable().updateNoteGuid(guid, newGuid);\r
1448                 conn.getNoteTable().updateNoteNotebook(newGuid, notebookGuid, true);\r
1449                 \r
1450                 noteSignal.notebookChanged.emit(newGuid, notebookGuid);\r
1451                 refreshNeeded = true;\r
1452                 noteSignal.guidChanged.emit(guid,newGuid);\r
1453         }\r
1454         \r
1455 \r
1456 \r
1457         \r
1458         //******************************************************\r
1459         //******************************************************\r
1460         //** Utility Functions\r
1461         //******************************************************\r
1462         //******************************************************\r
1463         // Convert a byte array to a hex string\r
1464         private static String byteArrayToHexString(byte data[]) {\r
1465                 StringBuffer buf = new StringBuffer();\r
1466             for (byte element : data) {\r
1467                 int halfbyte = (element >>> 4) & 0x0F;\r
1468                 int two_halfs = 0;\r
1469                 do {\r
1470                         if ((0 <= halfbyte) && (halfbyte <= 9))\r
1471                                buf.append((char) ('0' + halfbyte));\r
1472                            else\r
1473                                 buf.append((char) ('a' + (halfbyte - 10)));\r
1474                         halfbyte = element & 0x0F;\r
1475                 } while(two_halfs++ < 1);\r
1476             }\r
1477             return buf.toString();              \r
1478         }\r
1479 \r
1480         \r
1481         \r
1482         //*******************************************************\r
1483         //* Find dirty tags, which do not have newly created parents\r
1484         //*******************************************************\r
1485         private Tag findNextTag() {\r
1486                 logger.log(logger.HIGH, "Entering SyncRunner.findNextTag");\r
1487                 Tag nextTag = null;\r
1488                 List<Tag> tags = conn.getTagTable().getDirty();\r
1489                 \r
1490                 // Find the parent.  If the parent has a sequence > 0 then it is a good\r
1491                 // parent.\r
1492                 for (int i=0; i<tags.size() && keepRunning; i++) {\r
1493                         if (!badTagSync.containsKey(tags.get(i).getGuid())) {\r
1494                                 if (tags.get(i).getParentGuid() == null) {\r
1495                                         logger.log(logger.HIGH, "Leaving SyncRunner.findNextTag - tag found without parent");\r
1496                                         return tags.get(i);\r
1497                                 }\r
1498                                 Tag parentTag = conn.getTagTable().getTag(tags.get(i).getParentGuid());\r
1499                                 if (parentTag.getUpdateSequenceNum() > 0) {\r
1500                                         logger.log(logger.HIGH, "Leaving SyncRunner.findNextTag - tag found");\r
1501                                         return tags.get(i);\r
1502                                 }\r
1503                         }\r
1504                 }\r
1505                 \r
1506                 logger.log(logger.HIGH, "Leaving SyncRunner.findNextTag - no tags returned");\r
1507                 return nextTag;\r
1508         }\r
1509         \r
1510         \r
1511            // Connect to Evernote\r
1512     public boolean enConnect()  {\r
1513         try {\r
1514                         userStoreTrans = new THttpClient(userStoreUrl);\r
1515                         userStoreTrans.setCustomHeader("User-Agent", userAgent);\r
1516                 } catch (TTransportException e) {\r
1517                         QMessageBox mb = new QMessageBox(QMessageBox.Icon.Critical, "Transport Excepton", e.getLocalizedMessage());\r
1518                         mb.exec();\r
1519                         e.printStackTrace();\r
1520                 }\r
1521                 userStoreProt = new TBinaryProtocol(userStoreTrans);\r
1522             userStore = new UserStore.Client(userStoreProt, userStoreProt);\r
1523             syncSignal.saveUserStore.emit(userStore);\r
1524             try {\r
1525                         //authResult = userStore.authenticate(username, password, consumerKey, consumerSecret);\r
1526                 user = userStore.getUser(authToken);\r
1527                 } catch (EDAMUserException e) {\r
1528                         QMessageBox mb = new QMessageBox(QMessageBox.Icon.Critical, "Error", "Invalid Authorization");\r
1529                         mb.exec();\r
1530                         isConnected = false;\r
1531                         return false;\r
1532                 } catch (EDAMSystemException e) {\r
1533                         QMessageBox mb = new QMessageBox(QMessageBox.Icon.Critical, "EDAM System Excepton", e.getLocalizedMessage());\r
1534                         mb.exec();\r
1535                         e.printStackTrace();\r
1536                         isConnected = false;\r
1537                 } catch (TException e) {\r
1538                         QMessageBox mb = new QMessageBox(QMessageBox.Icon.Critical, "Transport Excepton", e.getLocalizedMessage());\r
1539                         mb.exec();\r
1540                         e.printStackTrace();\r
1541                         isConnected = false;\r
1542                 }\r
1543                 \r
1544             boolean versionOk = false;\r
1545                 try {\r
1546                         versionOk = userStore.checkVersion("NixNote", \r
1547                     com.evernote.edam.userstore.Constants.EDAM_VERSION_MAJOR, \r
1548                       com.evernote.edam.userstore.Constants.EDAM_VERSION_MINOR);\r
1549                 } catch (TException e) {\r
1550                         e.printStackTrace();\r
1551                         isConnected = false;\r
1552                 } \r
1553             if (!versionOk) { \r
1554                 System.err.println("Incomatible EDAM client protocol version"); \r
1555                 isConnected = false;\r
1556             }\r
1557             //if (authResult != null) {\r
1558                 //user = authResult.getUser(); \r
1559                 //authToken = authResult.getAuthenticationToken(); \r
1560                 noteStoreUrl = noteStoreUrlBase + user.getShardId();\r
1561                 syncSignal.saveAuthToken.emit(authToken);\r
1562                 syncSignal.saveNoteStore.emit(localNoteStore);\r
1563                 \r
1564          \r
1565                 try {\r
1566                         noteStoreTrans = new THttpClient(noteStoreUrl);\r
1567                         noteStoreTrans.setCustomHeader("User-Agent", userAgent);\r
1568                 } catch (TTransportException e) {\r
1569                         QMessageBox mb = new QMessageBox(QMessageBox.Icon.Critical, "Transport Excepton", e.getLocalizedMessage());\r
1570                         mb.exec();\r
1571                         e.printStackTrace();\r
1572                         isConnected = false;\r
1573                 } \r
1574                 noteStoreProt = new TBinaryProtocol(noteStoreTrans);\r
1575                 localNoteStore = \r
1576                         new NoteStore.Client(noteStoreProt, noteStoreProt); \r
1577                 isConnected = true;\r
1578                 //authTimeRemaining = authResult.getExpiration() - authResult.getCurrentTime();\r
1579                 //authRefreshTime = authTimeRemaining / 2;\r
1580             //}\r
1581             \r
1582                 // Get user information\r
1583                 try {\r
1584                         User user = userStore.getUser(authToken);\r
1585                         syncSignal.saveUserInformation.emit(user);\r
1586                 } catch (EDAMUserException e1) {\r
1587                         e1.printStackTrace();\r
1588                 } catch (EDAMSystemException e1) {\r
1589                         e1.printStackTrace();\r
1590                 } catch (TException e1) {\r
1591                         e1.printStackTrace();\r
1592                 }\r
1593             \r
1594             return isConnected;\r
1595     }\r
1596         // Disconnect from the database                         \r
1597     public void enDisconnect() {\r
1598         isConnected = false;\r
1599     }\r
1600     \r
1601     /*\r
1602     // Refresh the connection\r
1603     private synchronized boolean refreshConnection() {\r
1604         \r
1605                 logger.log(logger.EXTREME, "Entering SyncRunner.refreshConnection()");\r
1606 //        Calendar cal = Calendar.getInstance();\r
1607                 \r
1608         // If we are not connected let's get out of here\r
1609         if (!isConnected)\r
1610                 return false;\r
1611         \r
1612                 // If we fail too many times, then let's give up.\r
1613                 if (failedRefreshes >=5) {\r
1614                         logger.log(logger.EXTREME, "Refresh attempts have failed.  Disconnecting.");\r
1615                         isConnected = false;\r
1616                         status.message.emit(tr("Unable to synchronize - Authentication failed"));\r
1617                         return false;\r
1618                 }\r
1619         \r
1620                 // If this is the first time through, then we need to set this\r
1621 //              if (authRefreshTime == 0 || cal.getTimeInMillis() > authRefreshTime) \r
1622 //                      authRefreshTime = cal.getTimeInMillis();\r
1623                 \r
1624  //             // Default to checking again in 5 min.  This in case we fail.\r
1625  //             authRefreshTime = authRefreshTime +(5*60*1000);     \r
1626 \r
1627                 // Try to get a new token\r
1628                 AuthenticationResult newAuth = null; \r
1629                 logger.log(logger.EXTREME, "Beginning to try authentication refresh");\r
1630         try {\r
1631                 if (userStore != null && authToken != null) \r
1632                         newAuth = userStore.refreshAuthentication(authToken); \r
1633                 else\r
1634                         return false;\r
1635                 logger.log(logger.EXTREME, "UserStore.refreshAuthentication has succeeded.");\r
1636                 } catch (EDAMUserException e) {\r
1637                         e.printStackTrace();\r
1638                         syncSignal.authRefreshComplete.emit(false);\r
1639                         failedRefreshes++;\r
1640                         return false;\r
1641                 } catch (EDAMSystemException e) {\r
1642                         e.printStackTrace();\r
1643                         syncSignal.authRefreshComplete.emit(false);\r
1644                         failedRefreshes++;\r
1645                         return false;           \r
1646                 } catch (TException e) { \r
1647                         e.printStackTrace();\r
1648                         syncSignal.authRefreshComplete.emit(false);\r
1649                         failedRefreshes++;\r
1650                         return false;\r
1651                 }\r
1652                 \r
1653                 // If we didn't get a good auth, then we've failed\r
1654                 if (newAuth == null) {\r
1655                         failedRefreshes++;\r
1656                         status.message.emit(tr("Unable to synchronize - Authentication failed"));\r
1657                         logger.log(logger.EXTREME, "Authentication failure #" +failedRefreshes);\r
1658                         status.message.emit(tr("Unable to synchronize - Authentication failed"));\r
1659                         syncSignal.authRefreshComplete.emit(false);\r
1660                         return false;\r
1661                 }\r
1662                 \r
1663                 // We got a good token.  Now we need to setup the time to renew it.\r
1664                 logger.log(logger.EXTREME, "Saving authentication tokens");\r
1665                 authResult = newAuth;\r
1666                 authToken = new String(newAuth.getAuthenticationToken());\r
1667 //              authTimeRemaining = authResult.getExpiration() - authResult.getCurrentTime();\r
1668 //              authRefreshTime = cal.getTimeInMillis() + (authTimeRemaining/4);        \r
1669                 failedRefreshes=0;\r
1670                 syncSignal.authRefreshComplete.emit(true);\r
1671                 authRefreshNeeded = false;\r
1672                         \r
1673                 // This should never happen, but if it does we consider this a faild attempt.\r
1674 //              if (authTimeRemaining <= 0) {\r
1675 //                      failedRefreshes++;\r
1676 //                      syncSignal.authRefreshComplete.emit(false);\r
1677 //              }\r
1678                 \r
1679                 return true;\r
1680     }\r
1681     \r
1682     */\r
1683     \r
1684         public synchronized boolean addWork(String request) {\r
1685                 if (workQueue.offer(request))\r
1686                         return true;\r
1687                 return false;\r
1688         }\r
1689     \r
1690     private Note getNoteContent(Note n) {\r
1691                 QTextCodec codec = QTextCodec.codecForLocale();\r
1692                 codec = QTextCodec.codecForName("UTF-8");\r
1693         n.setContent(codec.toUnicode(new QByteArray(n.getContent())));\r
1694         return n;\r
1695     }\r
1696 \r
1697 \r
1698 \r
1699     //*********************************************************\r
1700     //* Special download instructions.  Used for DB upgrades\r
1701     //*********************************************************\r
1702     private void downloadAllSharedNotebooks(Client noteStore) {\r
1703         try {\r
1704                         List<SharedNotebook> books = noteStore.listSharedNotebooks(authToken);\r
1705                         logger.log(logger.LOW, "Shared notebooks found = " +books.size());\r
1706                         for (int i=0; i<books.size(); i++) {\r
1707                                 conn.getSharedNotebookTable().updateNotebook(books.get(i), false);\r
1708                         }\r
1709                         conn.getSyncTable().deleteRecord("FullSharedNotebookSync");\r
1710                 } catch (EDAMUserException e1) {\r
1711                         e1.printStackTrace();\r
1712                         status.message.emit(tr("User exception Listing shared notebooks."));\r
1713                         logger.log(logger.LOW, e1.getMessage());\r
1714                         return;\r
1715                 } catch (EDAMSystemException e1) {\r
1716                         e1.printStackTrace();\r
1717                         status.message.emit(tr("System exception Listing shared notebooks."));\r
1718                         logger.log(logger.LOW, e1.getMessage());\r
1719                         return;\r
1720                 } catch (TException e1) {\r
1721                         e1.printStackTrace();\r
1722                         status.message.emit(tr("Transaction exception Listing shared notebooks."));\r
1723                         logger.log(logger.LOW, e1.getMessage());\r
1724                         return;\r
1725                 } catch (EDAMNotFoundException e1) {\r
1726                         e1.printStackTrace();\r
1727                         status.message.emit(tr("EDAM Not Found exception Listing shared notebooks."));\r
1728                         logger.log(logger.LOW, e1.getMessage());\r
1729                 }\r
1730     }\r
1731     private void downloadAllNotebooks(Client noteStore) {\r
1732         try {\r
1733                         List<Notebook> books = noteStore.listNotebooks(authToken);\r
1734                         logger.log(logger.LOW, "Shared notebooks found = " +books.size());\r
1735                         for (int i=0; i<books.size(); i++) {\r
1736                                 conn.getNotebookTable().updateNotebook(books.get(i), false);\r
1737                         }\r
1738                         conn.getSyncTable().deleteRecord("FullNotebookSync");\r
1739                 } catch (EDAMUserException e1) {\r
1740                         e1.printStackTrace();\r
1741                         status.message.emit(tr("User exception Listing notebooks."));\r
1742                         logger.log(logger.LOW, e1.getMessage());\r
1743                         return;\r
1744                 } catch (EDAMSystemException e1) {\r
1745                         e1.printStackTrace();\r
1746                         status.message.emit(tr("System exception Listing notebooks."));\r
1747                         logger.log(logger.LOW, e1.getMessage());\r
1748                         return;\r
1749                 } catch (TException e1) {\r
1750                         e1.printStackTrace();\r
1751                         status.message.emit(tr("Transaction exception Listing notebooks."));\r
1752                         logger.log(logger.LOW, e1.getMessage());\r
1753                         return;\r
1754                 }\r
1755     }\r
1756     private void downloadAllLinkedNotebooks(Client noteStore) {\r
1757         try {\r
1758                         List<LinkedNotebook> books = noteStore.listLinkedNotebooks(authToken);\r
1759                         logger.log(logger.LOW, "Linked notebooks found = " +books.size());\r
1760                         for (int i=0; i<books.size(); i++) {\r
1761                                 conn.getLinkedNotebookTable().updateNotebook(books.get(i), false);\r
1762                         }\r
1763                         conn.getSyncTable().deleteRecord("FullLinkedNotebookSync");\r
1764                 } catch (EDAMUserException e1) {\r
1765                         e1.printStackTrace();\r
1766                         status.message.emit(tr("User exception Listing linked notebooks."));\r
1767                         logger.log(logger.LOW, e1.getMessage());\r
1768                         return;\r
1769                 } catch (EDAMSystemException e1) {\r
1770                         e1.printStackTrace();\r
1771                         status.message.emit(tr("System exception Listing linked notebooks."));\r
1772                         logger.log(logger.LOW, e1.getMessage());\r
1773                         return;\r
1774                 } catch (TException e1) {\r
1775                         e1.printStackTrace();\r
1776                         status.message.emit(tr("Transaction exception Listing lineked notebooks."));\r
1777                         logger.log(logger.LOW, e1.getMessage());\r
1778                         return;\r
1779                 } catch (EDAMNotFoundException e1) {\r
1780                         e1.printStackTrace();\r
1781                         status.message.emit(tr("EDAM Not Found exception Listing linked notebooks."));\r
1782                         logger.log(logger.LOW, e1.getMessage());\r
1783                 }\r
1784     }\r
1785 \r
1786     \r
1787     private void downloadInkNoteImage(String guid, String authToken) {\r
1788                 String urlBase = noteStoreUrl.replace("/edam/note/", "/shard/") + "/res/"+guid+".ink?slice=";\r
1789 //              urlBase = "https://www.evernote.com/shard/s1/res/52b567a9-54ae-4a08-afc5-d5bae275b2a8.ink?slice=";\r
1790                 Integer slice = 1;\r
1791                 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, false);\r
1792                 conn.getInkImagesTable().expungeImage(r.getGuid());\r
1793                 int sliceCount = 1+((r.getHeight()-1)/480);\r
1794                 HttpClient http = new DefaultHttpClient();\r
1795         for (int i=0; i<sliceCount; i++) {\r
1796                 String url = urlBase + slice.toString();\r
1797                 HttpPost post = new HttpPost(url);\r
1798                 post.getParams().setParameter("auth", authToken);\r
1799                 List <NameValuePair> nvps = new ArrayList <NameValuePair>();\r
1800             nvps.add(new BasicNameValuePair("auth", authToken));\r
1801 \r
1802             try {\r
1803                                 post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));\r
1804                         } catch (UnsupportedEncodingException e1) {\r
1805                                 e1.printStackTrace();\r
1806                         }\r
1807                 try {\r
1808                         HttpResponse response = http.execute(post);\r
1809                         HttpEntity resEntity = response.getEntity();\r
1810                         InputStream is = resEntity.getContent();\r
1811                         QByteArray data = writeToFile(is);\r
1812                         conn.getInkImagesTable().saveImage(guid, slice, data);\r
1813                         } catch (ClientProtocolException e) {\r
1814                                 e.printStackTrace();\r
1815                         } catch (IOException e) {\r
1816                                 e.printStackTrace();\r
1817                         }\r
1818 \r
1819                         slice++;\r
1820         }\r
1821         http.getConnectionManager().shutdown(); \r
1822                 noteSignal.noteChanged.emit(r.getNoteGuid(), null);   // Signal to ivalidate note cache\r
1823     }\r
1824     \r
1825     \r
1826     public QByteArray writeToFile(InputStream iStream) throws IOException {\r
1827 \r
1828             File temp = File.createTempFile("nn-inknote-temp", ".png");\r
1829 \r
1830             // Save InputStream to the file.\r
1831             BufferedOutputStream fOut = null;\r
1832             try {\r
1833               fOut = new BufferedOutputStream(new FileOutputStream(temp));\r
1834               byte[] buffer = new byte[32 * 1024];\r
1835               int bytesRead = 0;\r
1836               while ((bytesRead = iStream.read(buffer)) != -1) {\r
1837                 fOut.write(buffer, 0, bytesRead);\r
1838               }\r
1839             }\r
1840             finally {\r
1841                 iStream.close();\r
1842                 fOut.close();\r
1843             }\r
1844             QFile tempFile = new QFile(temp.getAbsoluteFile().toString());\r
1845             tempFile.open(OpenModeFlag.ReadOnly);\r
1846             QByteArray data = tempFile.readAll();\r
1847             tempFile.close();\r
1848             tempFile.remove();\r
1849             return data;\r
1850     }\r
1851     \r
1852     \r
1853         //******************************************\r
1854         //* Begin syncing shared notebooks \r
1855         //******************************************\r
1856     private void syncLinkedNotebooks() {\r
1857         logger.log(logger.MEDIUM, "Authenticating linked Notebooks");\r
1858         status.message.emit(tr("Synchronizing shared notebooks."));\r
1859         List<LinkedNotebook> books = conn.getLinkedNotebookTable().getAll();\r
1860         \r
1861         errorSharedNotebooks.clear();\r
1862                 \r
1863         for (int i=0; i<books.size(); i++) {\r
1864                 if (errorSharedNotebooksIgnored.containsKey(books.get(i).getGuid()))\r
1865                         break;\r
1866                 try {\r
1867                         logger.log(logger.EXTREME, "Checking notebook: " +books.get(i).getShareName());\r
1868                                 long lastSyncDate = conn.getLinkedNotebookTable().getLastSequenceDate(books.get(i).getGuid());\r
1869                                 int lastSequenceNumber = conn.getLinkedNotebookTable().getLastSequenceNumber(books.get(i).getGuid());\r
1870 \r
1871                                 logger.log(logger.EXTREME, "Last Sequence Number on file: " +lastSequenceNumber);\r
1872                                 \r
1873                                 // Authenticate to the owner's shard\r
1874                                 String linkedNoteStoreUrl       = noteStoreUrlBase + books.get(i).getShardId();\r
1875                                 logger.log(logger.EXTREME, "linkedNoteStoreURL: " +linkedNoteStoreUrl);\r
1876                                 THttpClient linkedNoteStoreTrans        = new THttpClient(linkedNoteStoreUrl);\r
1877                                 TBinaryProtocol linkedNoteStoreProt     = new TBinaryProtocol(linkedNoteStoreTrans);\r
1878                                 Client linkedNoteStore = new NoteStore.Client(linkedNoteStoreProt, linkedNoteStoreProt);        \r
1879 \r
1880                                 linkedAuthResult = null;\r
1881                                 if (books.get(i).getShareKey() != null) {\r
1882                                         logger.log(logger.EXTREME, "Share Key Not Null: " +books.get(i).getShareKey());\r
1883                                         linkedAuthResult = linkedNoteStore.authenticateToSharedNotebook(books.get(i).getShareKey(), authToken);\r
1884                                         logger.log(logger.EXTREME, "Authentication Token" +linkedAuthResult.getAuthenticationToken());\r
1885                                 } else {\r
1886                                         logger.log(logger.EXTREME, "Share key is null");\r
1887                                         linkedAuthResult = new AuthenticationResult();\r
1888                                         linkedAuthResult.setAuthenticationToken("");\r
1889                                 }\r
1890                                 SyncState linkedSyncState = \r
1891                                         linkedNoteStore.getLinkedNotebookSyncState(linkedAuthResult.getAuthenticationToken(), books.get(i));\r
1892                                 if (linkedSyncState.getUpdateCount() > lastSequenceNumber) {\r
1893                                         logger.log(logger.EXTREME, "Remote changes found");\r
1894                                         if (lastSyncDate < linkedSyncState.getFullSyncBefore()) {\r
1895                                                 lastSequenceNumber = 0;\r
1896                                         } \r
1897                                         logger.log(logger.EXTREME, "Calling syncLinkedNotebook for " +books.get(i).getShareName());\r
1898                                         syncLinkedNotebook(linkedNoteStore, books.get(i), \r
1899                                                         lastSequenceNumber, linkedSyncState.getUpdateCount(), authToken);\r
1900                                 }\r
1901                         \r
1902                         // Synchronize local changes\r
1903                         syncLocalLinkedNoteChanges(linkedNoteStore, books.get(i));\r
1904                                 \r
1905                 } catch (EDAMUserException e) {\r
1906                         e.printStackTrace();\r
1907                 } catch (EDAMNotFoundException e) {\r
1908                         status.message.emit(tr("Error synchronizing \" " +\r
1909                                         books.get(i).getShareName()+"\". Please verify you still have access to that shared notebook."));\r
1910                         errorSharedNotebooks.add(books.get(i).getGuid());\r
1911                         errorSharedNotebooksIgnored.put(books.get(i).getGuid(), books.get(i).getGuid());\r
1912                         logger.log(logger.LOW, "Error synchronizing shared notebook.  EDAMNotFound: "+e.getMessage());\r
1913                         logger.log(logger.LOW, e.getStackTrace());\r
1914                         error = true;\r
1915                         e.printStackTrace();\r
1916                 } catch (EDAMSystemException e) {\r
1917                         error = true;\r
1918                         logger.log(logger.LOW, "System error authenticating against shared notebook. "+\r
1919                                         "Key: "+books.get(i).getShareKey() +" Error:" +e.getMessage());\r
1920                         e.printStackTrace();\r
1921                 } catch (TException e) {\r
1922                         error = true;\r
1923                         e.printStackTrace();\r
1924                 }\r
1925         }\r
1926         \r
1927         // Cleanup tags\r
1928         conn.getTagTable().removeUnusedLinkedTags();\r
1929         conn.getTagTable().cleanupTags();\r
1930         tagSignal.listChanged.emit();\r
1931         return;\r
1932         }\r
1933 \r
1934     \r
1935     //**************************************************************\r
1936     //* Linked notebook contents (from someone else's account)\r
1937     //*************************************************************\r
1938         private void syncLinkedNotebook(Client linkedNoteStore, LinkedNotebook book, int usn, int highSequence, String token) {\r
1939                 logger.log(logger.EXTREME, "Entering syncLinkedNotebook");\r
1940                 if (ignoreLinkedNotebooks.contains(book.getGuid()))\r
1941                         return;\r
1942                 List<Note> dirtyNotes = conn.getNoteTable().getDirtyLinkedNotes();\r
1943                 if (dirtyNoteGuids == null) \r
1944                         dirtyNoteGuids = new Vector<String>();\r
1945 \r
1946                 for (int i=0; i<dirtyNotes.size() && keepRunning; i++) {\r
1947                         dirtyNoteGuids.add(dirtyNotes.get(i).getGuid());\r
1948                 }\r
1949                 boolean fullSync = false;\r
1950                 if (usn == 0)\r
1951                         fullSync = true;\r
1952                 boolean syncError = false;\r
1953                 while (usn < highSequence && !syncError) {\r
1954                         refreshNeeded = true;\r
1955                         try {\r
1956                                 SyncChunk chunk = \r
1957                                         linkedNoteStore.getLinkedNotebookSyncChunk(token, book, usn, 10, fullSync);\r
1958                                 \r
1959                                 // Expunge notes\r
1960                                 syncExpungedNotes(chunk);\r
1961 \r
1962                                 logger.log(logger.EXTREME, "Syncing remote notes: " +chunk.getNotesSize());\r
1963                                 syncRemoteNotes(linkedNoteStore, chunk.getNotes(), fullSync, linkedAuthResult.getAuthenticationToken());\r
1964                                 logger.log(logger.EXTREME, "Finding new linked tags");\r
1965                                 findNewLinkedTags(linkedNoteStore, chunk.getNotes(), linkedAuthResult.getAuthenticationToken());\r
1966                                 // Sync resources\r
1967                                 logger.log(logger.EXTREME, "Synchronizing tags: " +chunk.getTagsSize());\r
1968                                 for (int i=0; i<chunk.getResourcesSize(); i++) {\r
1969                                         syncRemoteResource(linkedNoteStore, chunk.getResources().get(i), linkedAuthResult.getAuthenticationToken());\r
1970                                 }\r
1971                                 logger.log(logger.EXTREME, "Synchronizing linked notebooks: " +chunk.getNotebooksSize());\r
1972                                 syncRemoteLinkedNotebooks(linkedNoteStore, chunk.getNotebooks(), false, book);\r
1973                                 syncLinkedTags(chunk.getTags(), book.getGuid());\r
1974                                 \r
1975                                 // Go through & signal any notes that have changed so we can refresh the user's view\r
1976                                 for (int i=0; i<chunk.getNotesSize(); i++) \r
1977                                         noteSignal.noteChanged.emit(chunk.getNotes().get(i).getGuid(), null);\r
1978 \r
1979                                 // Expunge Notebook records\r
1980                                 logger.log(logger.EXTREME, "Expunging linked notebooks: " +chunk.getExpungedLinkedNotebooksSize());\r
1981                                 for (int i=0; i<chunk.getExpungedLinkedNotebooksSize(); i++) {\r
1982                                         conn.getLinkedNotebookTable().expungeNotebook(chunk.getExpungedLinkedNotebooks().get(i), false);\r
1983                                 }\r
1984                                 usn = chunk.getChunkHighUSN();\r
1985                                 conn.getLinkedNotebookTable().setLastSequenceDate(book.getGuid(),chunk.getCurrentTime());\r
1986                                 conn.getLinkedNotebookTable().setLastSequenceNumber(book.getGuid(),chunk.getChunkHighUSN());\r
1987                         } catch (EDAMUserException e) {\r
1988                                 syncError = true;\r
1989                                 status.message.emit(tr("EDAM UserException synchronizing linked notbook.  See the log for datails."));\r
1990                                 e.printStackTrace();\r
1991                                 logger.log(logger.LOW, tr("EDAM UserException synchronizing linked notbook ")+ e.getMessage());\r
1992                         } catch (EDAMSystemException e) {\r
1993                                 syncError = true;\r
1994                                 status.message.emit(tr("EDAM SystemException synchronizing linked notbook.  See the log for datails."));\r
1995                                 e.printStackTrace();\r
1996                                 logger.log(logger.LOW, tr("EDAM SystemException synchronizing linked notbook.  See the log for datails") +e.getMessage());\r
1997                         } catch (EDAMNotFoundException e) {\r
1998                                 syncError = true;\r
1999                                 status.message.emit(tr("Notebook URL not found. Removing notobook ") +book.getShareName());\r
2000                                 conn.getNotebookTable().deleteLinkedTags(book.getGuid());\r
2001                                 conn.getLinkedNotebookTable().expungeNotebook(book.getGuid(), false);\r
2002                                 logger.log(logger.LOW, tr("Notebook URL not found. Removing notobook ") +e.getMessage());\r
2003                         } catch (TException e) {\r
2004                                 syncError = true;\r
2005                                 status.message.emit(tr("EDAM TException synchronizing linked notbook.  See the log for datails."));\r
2006                                 e.printStackTrace();\r
2007                                 logger.log(logger.LOW, tr("EDAM TException synchronizing linked notbook.  See the log for datails." )+e.getMessage());\r
2008                         }\r
2009                 }\r
2010                 logger.log(logger.EXTREME, "leaving syncLinkedNotebook");\r
2011         }\r
2012         // Sync remote tags\r
2013         private void syncLinkedTags(List<Tag> tags, String notebookGuid) {\r
2014                 logger.log(logger.EXTREME, "Entering SyncRunner.syncRemoteTags");\r
2015                 if (tags != null) {\r
2016                         for (int i=0; i<tags.size() && keepRunning; i++) {\r
2017                                 conn.getTagTable().syncLinkedTag(tags.get(i), notebookGuid, false);\r
2018                         }\r
2019                 }\r
2020                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncRemoteTags");\r
2021         }\r
2022         \r
2023         // Sync notebooks from a linked notebook\r
2024         private void syncRemoteLinkedNotebooks(Client noteStore, List<Notebook> notebooks, boolean readOnly, LinkedNotebook linked) {\r
2025                 logger.log(logger.EXTREME, "Entering SyncRunner.syncRemoteNotebooks");\r
2026                 if (notebooks != null) {\r
2027                         for (int i=0; i<notebooks.size() && keepRunning; i++) {\r
2028                                 try {\r
2029                                         logger.log(logger.EXTREME, "auth token:" +linkedAuthResult.getAuthenticationToken());\r
2030                                         if (!linkedAuthResult.getAuthenticationToken().equals("")) {\r
2031                                                 SharedNotebook s = noteStore.getSharedNotebookByAuth(linkedAuthResult.getAuthenticationToken());\r
2032                                                 logger.log(logger.EXTREME, "share key:"+s.getShareKey() +" notebookGuid" +s.getNotebookGuid());\r
2033                                                 conn.getLinkedNotebookTable().setNotebookGuid(s.getShareKey(), s.getNotebookGuid());\r
2034                                                 readOnly = !s.isNotebookModifiable();\r
2035                                         } else {\r
2036                                                 readOnly = true;\r
2037                                         }\r
2038                                         notebooks.get(i).setName(linked.getShareName());\r
2039                                         notebooks.get(i).setDefaultNotebook(false);\r
2040                                         conn.getNotebookTable().syncLinkedNotebook(notebooks.get(i), false, readOnly); \r
2041                                 } catch (EDAMUserException e) {\r
2042                                         readOnly = true;\r
2043                                         e.printStackTrace();\r
2044                                 } catch (EDAMNotFoundException e) {\r
2045                                         readOnly = true;\r
2046                                         e.printStackTrace();\r
2047                                 } catch (EDAMSystemException e) {\r
2048                                         readOnly = true;\r
2049                                         e.printStackTrace();\r
2050                                 } catch (TException e) {\r
2051                                         readOnly = true;\r
2052                                         e.printStackTrace();\r
2053                                 }\r
2054 \r
2055                         }\r
2056                 }                       \r
2057                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncRemoteNotebooks");\r
2058         }\r
2059 \r
2060         private void findNewLinkedTags(Client noteStore, List<Note> newNotes, String token) {\r
2061                 if (newNotes == null)\r
2062                         return;\r
2063                 for (int i=0; i<newNotes.size(); i++) {\r
2064                         Note n = newNotes.get(i);\r
2065                         for (int j=0; j<n.getTagGuidsSize(); j++) {\r
2066                                 String tag = n.getTagGuids().get(j);\r
2067                                 if (!conn.getTagTable().exists(tag)) {\r
2068                                         Tag newTag;\r
2069                                         try {\r
2070                                                 newTag = noteStore.getTag(token, tag);\r
2071                                                 conn.getTagTable().addTag(newTag, false);\r
2072                                         } catch (EDAMUserException e) {\r
2073                                                 e.printStackTrace();\r
2074                                         } catch (EDAMSystemException e) {\r
2075                                                 e.printStackTrace();\r
2076                                         } catch (EDAMNotFoundException e) {\r
2077                                                 e.printStackTrace();\r
2078                                         } catch (TException e) {\r
2079                                                 e.printStackTrace();\r
2080                                         }\r
2081                                         \r
2082                                 }\r
2083                         }\r
2084                 }\r
2085         }\r
2086 \r
2087         // Synchronize changes locally done to linked notes\r
2088         private void syncLocalLinkedNoteChanges(Client noteStore, LinkedNotebook book) {\r
2089                 logger.log(logger.EXTREME, "Entering SyncRunner.synclocalLinkedNoteChanges");\r
2090                 String notebookGuid = conn.getLinkedNotebookTable().getNotebookGuid(book.getGuid());\r
2091                 logger.log(logger.EXTREME, "Finding changes for " +book.getShareName() +":" +book.getGuid() + ":" +notebookGuid);\r
2092                 List<Note> notes = conn.getNoteTable().getDirtyLinked(notebookGuid);\r
2093                 logger.log(logger.EXTREME, "Number of changes found: " +notes.size());\r
2094                 for (int i=0; i<notes.size(); i++) {\r
2095                         logger.log(logger.EXTREME, "Calling syncLocalNote with key " +linkedAuthResult.getAuthenticationToken());\r
2096                         syncLocalNote(noteStore, notes.get(i), linkedAuthResult.getAuthenticationToken());\r
2097                 }\r
2098                 logger.log(logger.EXTREME, "Leaving SyncRunner.synclocalLinkedNoteChanges");\r
2099         }\r
2100 \r
2101 }\r