DriveClient.js 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009
  1. /**
  2. * Copyright (c) 2006-2017, JGraph Ltd
  3. * Copyright (c) 2006-2017, Gaudenz Alder
  4. */
  5. DriveClient = function(editorUi)
  6. {
  7. mxEventSource.call(this);
  8. /**
  9. * Holds a reference to the UI. Needed for the sharing client.
  10. */
  11. this.ui = editorUi;
  12. // New mime type for XML files
  13. this.xmlMimeType = 'application/vnd.jgraph.mxfile';
  14. if (this.ui.editor.isChromelessView() && urlParams['rt'] != '1')
  15. {
  16. // Workaround for Google Drive requiring the user to click on the file in the
  17. // drive UI when not using this scope (user other scope with rt=1 URL param)
  18. this.appId = '850530949725';
  19. this.clientId = '850530949725.apps.googleusercontent.com';
  20. this.scopes = ['https://www.googleapis.com/auth/drive.readonly', 'openid'];
  21. // Only used for writing files which is disabled in viewer app
  22. this.mimeType = 'all_types_supported';
  23. }
  24. else if (this.ui.isDriveDomain())
  25. {
  26. this.appId = '671128082532';
  27. this.clientId = '671128082532.apps.googleusercontent.com';
  28. this.mimeType = 'application/vnd.jgraph.mxfile.realtime';
  29. }
  30. else
  31. {
  32. // Uses a different mime-type and realtime model than the drive domain
  33. // because realtime models for different app IDs are not compatible
  34. this.appId = '420247213240';
  35. this.clientId = '420247213240-hnbju1pt13seqrc1hhd5htpotk4g9q7u.apps.googleusercontent.com';
  36. this.mimeType = 'application/vnd.jgraph.mxfile.rtlegacy';
  37. }
  38. this.mimeTypes = this.xmlMimeType + 'application/mxe,application/mxr,' +
  39. 'application/vnd.jgraph.mxfile.realtime,application/vnd.jgraph.mxfile.rtlegacy';
  40. };
  41. // Extends mxEventSource
  42. mxUtils.extend(DriveClient, mxEventSource);
  43. /**
  44. * OAuth 2.0 scopes for installing Drive Apps.
  45. */
  46. DriveClient.prototype.scopes = (urlParams['photos'] == '1') ?
  47. ['https://www.googleapis.com/auth/drive.file',
  48. 'https://www.googleapis.com/auth/drive.install',
  49. 'https://www.googleapis.com/auth/photos',
  50. 'https://www.googleapis.com/auth/photos.upload',
  51. 'https://www.googleapis.com/auth/userinfo.profile'] :
  52. ['https://www.googleapis.com/auth/drive.file',
  53. 'https://www.googleapis.com/auth/drive.install',
  54. 'https://www.googleapis.com/auth/userinfo.profile'];
  55. /**
  56. * Contains the hostname of the old app.
  57. */
  58. DriveClient.prototype.allFields = 'kind,id,parents,headRevisionId,etag,title,mimeType,modifiedDate,' +
  59. 'editable,copyable,labels,properties,downloadUrl,webContentLink,userPermission';
  60. /**
  61. * Specifies if thumbnails should be enabled. Default is true.
  62. * LATER: If thumbnails are disabled, make sure to replace the
  63. * existing thumbnail with the placeholder only once.
  64. */
  65. DriveClient.prototype.enableThumbnails = true;
  66. /**
  67. * Specifies the width for thumbnails. Default is 1000. This value
  68. * must be between 220 and 1600.
  69. */
  70. DriveClient.prototype.thumbnailWidth = 1000;
  71. /**
  72. * The maximum number of bytes per thumbnail. Default is 2000000.
  73. */
  74. DriveClient.prototype.maxThumbnailSize = 2000000;
  75. /**
  76. * Defines the base64url PNG to be used if no thumbnail was generated
  77. * (including the case where thumbnails are disabled).
  78. */
  79. DriveClient.prototype.placeholderThumbnail = 'iVBORw0KGgoAAAANSUhEUgAAAJYAAACWCAMAAAAL34HQAAACN1BMVEXwhwXvhgX4iwXzhwXgbQzvhgXhbAzocgzqcwzldAoAAADhbgvjcQnmdgrlbgDwhgXsfwXufgjwhgXwgQfziAXxgADibgz4iwX4jAX3iwTpcwr1igXoewjsfgj3igX4iwXqcQv4jAX3iwXtfQnndQrvhAbibArwhwXgbQz//////v39jwX6jQX+/v7fagHfawzdVQDwhADgbhPgbhXwhwPocQ3uvKvwiA/faQDscgzxiAT97+XgciTgcSP6jAXgbQ3gcCHwiRfpcQzwhwfeXQD77ef74NLvhgTvegD66uPgbAf66+TvfADwjCzgcCfwiSD67ObhcjjwiBHhczvwiyrgbxj///777ujgcSHgcB/xiRzgbhveWgDeVwDhdEDgbRDqfgffYgDfXwD97+bvfQDxiz7//vvwiRr118rrcgztggbfZgDfZAD++PT98+3gbBPsgAb99vD33tPgcB7icAvuhAX//Pn66N/00sTyy7vuuqbjekLwhwzkcgr88er449n++vfutp/kh1vgcBvhbwvmdwnwgwDwgADeWQD87eLxxrTssJjqpIf0roHmjWTkhFP759n63czvvanomnjnlHDhczD22cr4y6/wwa/3xKX2wJ3rqpH0tY7qp4vpnoDymlbjf0vxjjntcwzldAroegj/kgX12s7518PzqnnnkWfynmLieUjpewjrdAD40Lj1uZTzpm3idTbiciLydQzzfwnyiQTsfgD3xqnzp3TxlkzgbCrdTwDdSwBLKUlNAAAAJ3RSTlP8/b2X/YH8wb+FAIuIggJbQin5opAM9+a/ubaubyD78NjSyr2WgRp4sjN4AAAI70lEQVR42u2cZ38SQRDGT8WGvfde4E4BxVMRRaKiUURRlJhQRDCCSgQVO/bee++9994+nMt5ywoezFJd/fm8uITi3p9n5mbYkcCpO6rVnVu2YEXd+3dRIySuo7pLv4GjGNKg7j3UHTl1l14PajmG9OFBnx7Ird4PumpYEtf1QXc112l0M7OGKXEfeg3guo3iNIyJG92Jaz61mYYxcaNacs1H/8f6j6X5j1WI/mMVIsawRFEzI49SjwOqAJa43emclk8Rp2c7AFZ+LDGyvXE2kmO2Q1Lq17RSd6ND48QIwFVuLNHTOPbEpTOz8ujMpccHGz0AV5mxIo4TpwUeUPj0YwfAVVYs0Tn7VZjnBUA8v+n6CyfERY8FR/DEJj7MQ6oL85vOvfDUAsuVC8s19s5yXuAppOPnvPk4EeSCsehCeBVTwVzHfE6RcFUQa4an8Qw91kpbw2oz4aoc1sSxniO0WAI/J24wriabmEpizZtM79bc+fr4/tUarEpiLabGElJYRsOGjbJfjGDpJCxtmosRLOEnVpqLESzZLYlLg65H1rAkLo2GESwcROwXI1jELcS1Y6OGQSzEVaupZQJLDiLhYtCtFBcbbslYhOueqKllDwtzwVhTq4RFuBh0C3EdEBl0C3OBWNUrEISLvSD+5GLQLYmLoSqfwcUiFuaqzhYDxiJc981lxqqdVsCGbHPcQLBgrtK3rwLt9tWqhblKxxI9hW3267U5ZHhuBrCKzXl4NIJTS5FrmbmMWGIEDZIouOp0/O6boYQ2jxBXWcdu13fzRILuF/2Ku+aGr96uBbhALHo5Z38+XcfXyVRZVx/+Ed513ldDCCCu0rFE0Xlo2mu5TAj8ki0XV0q6ePHilhi+d/15b9ACQGGusg3AFzc+XSMBCPzu89+CNlnB7zfD8t1z4iaLXUvDVT6sGdMOnv5pi47f6r9Qk9YF3xZ0l8S11UfMArlgLMpZM6bamYy6rWnta9q7TrZrzZPgPgoqg3atubY8WK6D8lQXHfb4p/wSK7vFfxmxSsAPQ96AlZ4LxoLNeompdkUDGQVznL5mLr4ar5ESD3PBWHA9fbpbjlT4pq1Bm6H6w9dwfOd69ePouNDYt3S3ULPGZ96S3YqtAW/Tepz1E8bgAANc+xEXhAX36ut1cslcd6rJq81SIvgEe7lmL3kY5iqxVYvOI9isswp22KeMOcrriJlWai5giwHl+yec73Ma9Mbfz+qOJndKz6hLpR5V1uPxavFuTTt0K1XfpbNeO0wKeUaR2IPBN5sMRlqu1eY8bsFmPeIFUpi0CjIGTLvSZY2EGeYSi3VL9Dgeb0I+SQl9MlcZT4TObZKzfmfS5NZSx1GsLQ5r+8Sxp7ERR/1TtDlUn2qNuGXCrZGM5URlLDiEVzDVkje5fdjXdDsm27XpXChBz4XG0UpYcDOMYaxjGc3wtyJxFtu1PohaI71f2K2imqEONcN4nrMZ9TWbMf81wg9z3VNwC26Gr3enY4ObobLqbccFefuz5AKONpVfzQp2y3NoVvrN32GLNl9orA22lTiM+Nqg5CJY1DueOjkwsdtNgAP7gidR2SWVhFqt3o9QwoKHIuiwDcwX+xT/UWztSlvCaqXGmtQBY1GadQmfh6anuE0XlkhhRFs3tGGkd+tuIVhiJN0M+brj0mlAu46lX0bcbizVLbgZrgwl4JhYA+NQa9TJQUetsSJYHscJvAVct7eJKoUbQudxPYmdirqzsYsIojhjoitD01yadH287J+vpZF1/uGt2K4ttinjshQo2C2XMzI2U64X6WY4tyZq99a7wZS3eA3BpNyrUPn1x00Z0uM1ACzilOfg7EN3VmRo8dN16WYYerYw6G9qCOSDCjQ0jQkufRbalt65LVyapaA/2mClxhK3Rxy3rsyavDxDR/DL5sMLFiyYu/7sXps7z8VldPv2Xl6PnjlTwOOuJQuytH7CXpvXCOQWoZrYeHWd4nw2Q+v22OLGnFSG0Nk1PCi0xjgjpVvTGi8hht9F+ARBGq8dtXmtOSLoDm1FhUSHnihkTecESalHkPAaWVhtFbA8jqvQGBmbt8fWkKtNn0Xw9GvAWK6DX9bBVHjzqtyvvcG9a+jXyC5oKoKV/a4YFG7Yij2ofszlgtaA3ZoRwW+pIOH3w0qZFURNh3oNtKsDsAr9LNvMC0pj93H6hTPpX9ocg8FIgTVvcgFYC03jFLBMi6ix0MDAoi8/lh7Cgt2q0VfNrSX0ayhjTa2IW0tKdotNrMq4NbPkILKZW+xdiSoGgshogfh7Ul7FcIEoFevfrPLC3+XWf6y/CEvHZoFQqlts9sQigqjLxFpQCJauakFcsqhKPXH79rGb6bE2B5Qmu0b91zn0WJtN8Wys9tgtIqfjEf2SWw7XKI8gHuKQ0X0eDsQSI44TaGBN6dYN5dlI/eFj9I7f8GWtoUJYOIgkiq6Ds/gw5T7dZDUqTrfscbLbB9eIB7JmEKsUgiii/4uO8ToBfJlhfif5tEGWEsGTMT4Mr6HDa0BBlP5Y88lcnkdkCtLhnyjMM0+Gcn2WzW6xnd/J8zn+LZq4SUeEvUBaA8LCs6Tk1p1AetXt3JoMWexWZSyr3RK6vSUGrRHbmkRUVgCLpP1HW/L4tgl5tO140mdKKFFhrkTUdxta4xleA8DCXC6n/vCYvPJFa9zAWL4m6qNaA8IiqjW73lreWnJrSj0AJYFZpvwq6RZRzjVUGEtB5tX7DdoqCXaL+PXHuEjdYsuvVqva4Sqv6NdabdW4YLeIKsoFYzHGhYPIGBd2izGuVpPaSVgAV7VEsOQgsuUXdosxLuwWxLVMW0WRK5ExLiiIpN4vq2YYVTiIbPmFgii5xRiXimCBqmIcVSS3WMqvdMqz5VcKqzdKeca4UrnVT/ryR6bi2Opuf64TwYJlfl4FLqu2Zxeux5BRXZnisvZ8103NqTtzoziuGa24+wZVRdVK9W7wyNSX1nYeOmrU6JSmjp6KhH5BR+kGvk++Ld0c/X66rPH4SEQeGl+kpq8a33eAumPqK347durWpzm9hrWhUevi1Hd4ZzVC+gGMHY0TYnDOYwAAAABJRU5ErkJggg=='.replace(/\+/g, '-').replace(/\//g, '_');
  80. /**
  81. * Mime type for the paceholder thumbnail.
  82. */
  83. DriveClient.prototype.placeholderMimeType = 'image/png';
  84. /**
  85. * Executes the first step for connecting to Google Drive.
  86. */
  87. DriveClient.prototype.libraryMimeType = 'application/vnd.jgraph.mxlibrary';
  88. /**
  89. * Contains the hostname of the new app.
  90. */
  91. DriveClient.prototype.newAppHostname = 'www.draw.io';
  92. /**
  93. * Contains the hostname of the old app.
  94. */
  95. DriveClient.prototype.oldAppHostname = 'legacy.draw.io';
  96. /**
  97. * Executes the first step for connecting to Google Drive.
  98. */
  99. DriveClient.prototype.extension = '.html';
  100. /**
  101. * Interval for updating the access token.
  102. */
  103. DriveClient.prototype.tokenRefreshInterval = 0;
  104. /**
  105. * Interval for updating the access token.
  106. */
  107. DriveClient.prototype.lastTokenRefresh = 0;
  108. /**
  109. * Executes the first step for connecting to Google Drive.
  110. */
  111. DriveClient.prototype.maxRetries = 4;
  112. /**
  113. * Executes the first step for connecting to Google Drive.
  114. */
  115. DriveClient.prototype.mimeTypeCheckCoolOff = 60000;
  116. /**
  117. * Executes the first step for connecting to Google Drive.
  118. */
  119. DriveClient.prototype.user = null;
  120. /**
  121. * Authorizes the client, gets the userId and calls <open>.
  122. */
  123. DriveClient.prototype.setUser = function(user)
  124. {
  125. this.user = user;
  126. if (this.user == null && this.tokenRefreshThread != null)
  127. {
  128. window.clearTimeout(this.tokenRefreshThread);
  129. this.tokenRefreshThread = null;
  130. }
  131. this.fireEvent(new mxEventObject('userChanged'));
  132. };
  133. /**
  134. * Authorizes the client, gets the userId and calls <open>.
  135. */
  136. DriveClient.prototype.getUser = function()
  137. {
  138. return this.user;
  139. };
  140. /**
  141. * Authorizes the client, gets the userId and calls <open>.
  142. */
  143. DriveClient.prototype.setUserId = function(userId, remember)
  144. {
  145. if (remember)
  146. {
  147. if (isLocalStorage)
  148. {
  149. localStorage.setItem('.guid', userId);
  150. }
  151. else if (typeof(Storage) != 'undefined')
  152. {
  153. try
  154. {
  155. var expiry = new Date();
  156. expiry.setYear(expiry.getFullYear() + 1);
  157. document.cookie = 'GUID=' + userId + '; expires=' + expiry.toUTCString();
  158. }
  159. catch (e)
  160. {
  161. // any errors for storing the user ID can be safely ignored
  162. }
  163. }
  164. }
  165. };
  166. /**
  167. * Authorizes the client, gets the userId and calls <open>.
  168. */
  169. DriveClient.prototype.clearUserId = function()
  170. {
  171. if (isLocalStorage)
  172. {
  173. localStorage.removeItem('.guid');
  174. }
  175. else if (typeof(Storage) != 'undefined')
  176. {
  177. var expiry = new Date();
  178. expiry.setYear(expiry.getFullYear() - 1);
  179. document.cookie = 'GUID=; expires=' + expiry.toUTCString();
  180. }
  181. };
  182. /**
  183. * Authorizes the client, gets the userId and calls <open>.
  184. */
  185. DriveClient.prototype.getUserId = function()
  186. {
  187. var uid = null;
  188. if (this.user != null)
  189. {
  190. uid = this.user.id;
  191. }
  192. if (uid == null && isLocalStorage)
  193. {
  194. uid = localStorage.getItem('.guid');
  195. }
  196. if (uid == null && typeof(Storage) != 'undefined')
  197. {
  198. var cookies = document.cookie.split(";");
  199. for (var i = 0; i < cookies.length; i++)
  200. {
  201. // Removes spaces around cookie
  202. var cookie = mxUtils.trim(cookies[i]);
  203. if (cookie.substring(0, 5) == 'GUID=')
  204. {
  205. uid = cookie.substring(5);
  206. break;
  207. }
  208. }
  209. if (uid != null && isLocalStorage)
  210. {
  211. // Moves to local storage
  212. var expiry = new Date();
  213. expiry.setYear(expiry.getFullYear() - 1);
  214. document.cookie = 'GUID=; expires=' + expiry.toUTCString();
  215. localStorage.setItem('.guid', uid);
  216. }
  217. }
  218. return uid;
  219. };
  220. /**
  221. * Authorizes the client, gets the userId and calls <open>.
  222. */
  223. DriveClient.prototype.execute = function(fn)
  224. {
  225. // Handles error in immediate authorize call via callback that shows a
  226. // UI with a button that executes the second non-immediate authorize
  227. var fallback = mxUtils.bind(this, function(resp)
  228. {
  229. // Remember is an argument for the callback that executes
  230. // when the user clicks the authorize button in the UI and
  231. // success executes after successful authorization.
  232. this.ui.showAuthDialog(this, true, mxUtils.bind(this, function(remember, success)
  233. {
  234. this.authorize(false, mxUtils.bind(this, function()
  235. {
  236. if (success != null)
  237. {
  238. success();
  239. }
  240. fn();
  241. }), mxUtils.bind(this, function(resp)
  242. {
  243. var msg = mxResources.get('cannotLogin');
  244. // Handles special domain policy errors
  245. if (resp != null && resp.error != null)
  246. {
  247. if (resp.error.code == 403 &&
  248. resp.error.data != null && resp.error.data.length > 0 &&
  249. resp.error.data[0].reason == 'domainPolicy')
  250. {
  251. msg = resp.error.message;
  252. }
  253. }
  254. this.ui.drive.clearUserId();
  255. this.ui.drive.setUser(null);
  256. gapi.auth.signOut();
  257. this.ui.showError(mxResources.get('error'), msg, mxResources.get('help'), mxUtils.bind(this, function()
  258. {
  259. this.ui.openLink('https://desk.draw.io/support/solutions/articles/16000074659');
  260. }), null, mxResources.get('ok'));
  261. }), remember);
  262. }));
  263. });
  264. // First immediate authorize attempt
  265. this.authorize(true, fn, fallback);
  266. };
  267. /**
  268. * Executes the given request.
  269. */
  270. DriveClient.prototype.executeRequest = function(req, success, error)
  271. {
  272. var acceptResponse = true;
  273. var timeoutThread = null;
  274. var retryCount = 0;
  275. // Cancels any pending requests
  276. if (this.requestThread != null)
  277. {
  278. window.clearTimeout(this.requestThread);
  279. }
  280. var fn = mxUtils.bind(this, function()
  281. {
  282. this.requestThread = null;
  283. this.currentRequest = req;
  284. if (timeoutThread != null)
  285. {
  286. window.clearTimeout(timeoutThread);
  287. }
  288. timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  289. {
  290. acceptResponse = false;
  291. if (error != null)
  292. {
  293. error({code: App.ERROR_TIMEOUT, retry: fn});
  294. }
  295. }), this.ui.timeout);
  296. req.execute(mxUtils.bind(this, function(resp)
  297. {
  298. window.clearTimeout(timeoutThread);
  299. if (acceptResponse)
  300. {
  301. if (resp != null && resp.error == null)
  302. {
  303. if (success != null)
  304. {
  305. success(resp);
  306. }
  307. }
  308. else
  309. {
  310. // Handles special error for saving old file where mime was changed to new
  311. // LATER: Check if 403 is never auth error, for now we check the message for a specific
  312. // case where the old app mime type was overridden by the new app
  313. if (error != null && resp != null && resp.error != null && resp.error.code == 403 &&
  314. (resp.error.message == 'The requested mime type change is forbidden.' ||
  315. resp.error.data != null && resp.error.data[0].reason == 'domainPolicy'))
  316. {
  317. error(resp);
  318. }
  319. // Handles authentication error
  320. else if (resp != null && resp.error != null && (resp.error.code == 401 || resp.error.code == 403))
  321. {
  322. // Shows an error if we're authenticated but the server still doesn't allow it
  323. if (resp.error.code == 403 && this.user != null)
  324. {
  325. if (error != null)
  326. {
  327. error(resp);
  328. }
  329. }
  330. else
  331. {
  332. this.execute(fn);
  333. }
  334. }
  335. // Schedules a retry if no new request was executed
  336. // TODO: Check for 'rateLimitExceeded', 'userRateLimitExceeded' in errors
  337. // see https://developers.google.com/drive/handle-errors
  338. else if (resp != null && resp.error != null && resp.error.code != 412 && resp.error.code != 404 &&
  339. this.currentRequest == req && retryCount < this.maxRetries)
  340. {
  341. retryCount++;
  342. var jitter = 1 + 0.1 * (Math.random() - 0.5);
  343. this.requestThread = window.setTimeout(fn, Math.round(Math.pow(2, retryCount) * jitter * 1000));
  344. }
  345. else if (error != null)
  346. {
  347. error(resp);
  348. }
  349. }
  350. }
  351. }));
  352. });
  353. // Must get token before first request in this case
  354. if (gapi.auth.getToken() == null)
  355. {
  356. this.execute(fn);
  357. }
  358. else
  359. {
  360. fn();
  361. }
  362. },
  363. /**
  364. * Authorizes the client, gets the userId and calls <open>.
  365. */
  366. DriveClient.prototype.authorize = function(immediate, success, error, remember)
  367. {
  368. var userId = this.getUserId();
  369. // Takes userId from state URL parameter
  370. if (this.ui.stateArg != null && this.ui.stateArg.userId != null)
  371. {
  372. userId = this.ui.stateArg.userId;
  373. }
  374. // Immediate only possible with userId
  375. if (immediate && userId == null)
  376. {
  377. if (error != null)
  378. {
  379. error();
  380. }
  381. }
  382. else
  383. {
  384. var params =
  385. {
  386. scope: this.scopes,
  387. client_id: this.clientId
  388. };
  389. if (immediate && userId != null)
  390. {
  391. params.immediate = true;
  392. params.user_id = userId;
  393. }
  394. else
  395. {
  396. params.immediate = false;
  397. params.authuser = -1;
  398. }
  399. gapi.auth.authorize(params, mxUtils.bind(this, function(resp)
  400. {
  401. // Updates the current user info
  402. if (resp != null && resp.error == null)
  403. {
  404. if (this.user == null || !immediate || this.user.id != userId)
  405. {
  406. this.updateUser(success, error, remember);
  407. }
  408. else if (success != null)
  409. {
  410. success();
  411. }
  412. }
  413. else if (error != null)
  414. {
  415. error(resp);
  416. }
  417. this.resetTokenRefresh(resp);
  418. }));
  419. }
  420. };
  421. /**
  422. * Checks if the client is authorized and calls the next step.
  423. */
  424. DriveClient.prototype.resetTokenRefresh = function(resp)
  425. {
  426. if (this.tokenRefreshThread != null)
  427. {
  428. window.clearTimeout(this.tokenRefreshThread);
  429. this.tokenRefreshThread = null;
  430. }
  431. // Starts timer to refresh token before it expires
  432. if (resp != null && resp.error == null && resp.expires_in > 0)
  433. {
  434. this.tokenRefreshInterval = parseInt(resp.expires_in) * 1000;
  435. this.lastTokenRefresh = new Date().getTime();
  436. this.tokenRefreshThread = window.setTimeout(mxUtils.bind(this, function()
  437. {
  438. this.authorize(true, mxUtils.bind(this, function()
  439. {
  440. //console.log('tokenRefresh: refreshed', gapi.auth.getToken());
  441. }), mxUtils.bind(this, function()
  442. {
  443. //console.log('tokenRefresh: error refreshing', gapi.auth.getToken());
  444. }));
  445. }), resp.expires_in * 900);
  446. }
  447. };
  448. /**
  449. * Checks if the client is authorized and calls the next step.
  450. */
  451. DriveClient.prototype.checkToken = function(fn)
  452. {
  453. var connected = this.lastTokenRefresh > 0;
  454. var delta = new Date().getTime() - this.lastTokenRefresh;
  455. if (delta > this.tokenRefreshInterval || this.tokenRefreshThread == null)
  456. {
  457. // Uses execute instead of authorize to allow a fallback authorization if cookie was lost
  458. this.execute(mxUtils.bind(this, function()
  459. {
  460. fn();
  461. if (connected)
  462. {
  463. this.fireEvent(new mxEventObject('disconnected'));
  464. }
  465. }));
  466. }
  467. else
  468. {
  469. fn();
  470. }
  471. };
  472. /**
  473. * Checks if the client is authorized and calls the next step.
  474. */
  475. DriveClient.prototype.updateUser = function(success, error, remember)
  476. {
  477. var token = gapi.auth.getToken().access_token;
  478. var url = 'https://www.googleapis.com/oauth2/v2/userinfo?alt=json&access_token=' + token;
  479. this.ui.loadUrl(url, mxUtils.bind(this, function(data)
  480. {
  481. var info = JSON.parse(data);
  482. // Requests more information about the user (email address is sometimes not in info)
  483. this.executeRequest(gapi.client.drive.about.get(), mxUtils.bind(this, function(resp)
  484. {
  485. this.setUser(new DrawioUser(info.id, resp.user.emailAddress, resp.user.displayName,
  486. (resp.user.picture != null) ? resp.user.picture.url : null, info.locale));
  487. this.setUserId(info.id, remember);
  488. if (success != null)
  489. {
  490. success();
  491. }
  492. }), error);
  493. }), error);
  494. };
  495. /**
  496. * Translates this point by the given vector.
  497. *
  498. * @param {number} dx X-coordinate of the translation.
  499. * @param {number} dy Y-coordinate of the translation.
  500. */
  501. DriveClient.prototype.copyFile = function(id, title, success, error)
  502. {
  503. if (id != null && title != null)
  504. {
  505. this.executeRequest(gapi.client.drive.files.copy({'fileId': id,
  506. 'fields': this.allFields, 'supportsTeamDrives': true,
  507. 'resource': {'title': title}}), success, error);
  508. }
  509. };
  510. /**
  511. * Translates this point by the given vector.
  512. *
  513. * @param {number} dx X-coordinate of the translation.
  514. * @param {number} dy Y-coordinate of the translation.
  515. */
  516. DriveClient.prototype.renameFile = function(id, title, success, error)
  517. {
  518. if (id != null && title != null)
  519. {
  520. this.executeRequest(this.createDriveRequest(
  521. id, {'title' : title}), success, error);
  522. }
  523. };
  524. /**
  525. * Translates this point by the given vector.
  526. *
  527. * @param {number} dx X-coordinate of the translation.
  528. * @param {number} dy Y-coordinate of the translation.
  529. */
  530. DriveClient.prototype.moveFile = function(id, folderId, success, error)
  531. {
  532. if (id != null && folderId != null)
  533. {
  534. this.executeRequest(this.createDriveRequest(id, {'parents': [{'kind':
  535. 'drive#fileLink', 'id': folderId}]}), success, error);
  536. }
  537. };
  538. /**
  539. * Translates this point by the given vector.
  540. *
  541. * @param {number} dx X-coordinate of the translation.
  542. * @param {number} dy Y-coordinate of the translation.
  543. */
  544. DriveClient.prototype.createDriveRequest = function(id, body)
  545. {
  546. return gapi.client.request({
  547. 'path': '/drive/v2/files/' + id,
  548. 'method': 'PUT',
  549. 'params': {'uploadType' : 'multipart', 'supportsTeamDrives': true},
  550. 'headers': {'Content-Type': 'application/json; charset=UTF-8'},
  551. 'body': JSON.stringify(body)
  552. });
  553. };
  554. /**
  555. * Loads the given file as a library file.
  556. */
  557. DriveClient.prototype.getLibrary = function(id, success, error)
  558. {
  559. return this.getFile(id, success, error, true, true);
  560. };
  561. /**
  562. * Loads the descriptorf for the given file ID.
  563. */
  564. DriveClient.prototype.loadDescriptor = function(id, success, error)
  565. {
  566. this.executeRequest(gapi.client.drive.files.get({'fileId': id,
  567. 'fields': this.allFields, 'supportsTeamDrives': true}),
  568. success, error);
  569. };
  570. /**
  571. * Gets the channel ID from the given descriptor.
  572. */
  573. DriveClient.prototype.getChannelId = function(desc)
  574. {
  575. var props = desc.properties;
  576. var result = null;
  577. if (props != null)
  578. {
  579. for (var i = 0; i < props.length; i++)
  580. {
  581. if (props[i].key == 'channel')
  582. {
  583. result = props[i].value;
  584. break;
  585. }
  586. }
  587. }
  588. return result;
  589. };
  590. /**
  591. * Checks if the client is authorized and calls the next step. The optional
  592. * readXml argument is used for import. Default is false. The optional
  593. * readLibrary argument is used for reading libraries. Default is false.
  594. */
  595. DriveClient.prototype.getFile = function(id, success, error, readXml, readLibrary)
  596. {
  597. readXml = (readXml != null) ? readXml : false;
  598. readLibrary = (readLibrary != null) ? readLibrary : false;
  599. if (urlParams['rev'] != null)
  600. {
  601. this.executeRequest(gapi.client.drive.revisions.get({'fileId': id,
  602. 'revisionId': urlParams['rev'], 'supportsTeamDrives': true}),
  603. mxUtils.bind(this, function(resp)
  604. {
  605. this.getXmlFile(resp, null, success, error);
  606. }), error);
  607. }
  608. else
  609. {
  610. this.loadDescriptor(id, mxUtils.bind(this, function(resp)
  611. {
  612. if (this.user != null)
  613. {
  614. var binary = /\.png$/i.test(resp.title);
  615. // Handles .vsdx, .vsd, .vdx, Gliffy and PNG+XML files by creating a temporary file
  616. if (/\.v(dx|sdx?)$/i.test(resp.title) || /\.gliffy$/i.test(resp.title) ||
  617. (!this.ui.useCanvasForExport && binary))
  618. {
  619. var url = resp.downloadUrl + '&access_token=' + gapi.auth.getToken().access_token;
  620. this.ui.convertFile(url, resp.title, resp.mimeType, this.extension, success, error);
  621. }
  622. else
  623. {
  624. // Handles converted realtime files as XML files
  625. if (readXml || readLibrary || resp.mimeType == this.libraryMimeType ||
  626. resp.mimeType == this.xmlMimeType)
  627. {
  628. this.getXmlFile(resp, null, success, error, true, readLibrary);
  629. }
  630. else
  631. {
  632. if (!App.GOOGLE_REALTIME)
  633. {
  634. if (this.isGoogleRealtimeMimeType(resp.mimeType))
  635. {
  636. this.convertRealtimeFile(resp, success, error);
  637. }
  638. else
  639. {
  640. this.getXmlFile(resp, null, success, error);
  641. }
  642. }
  643. else
  644. {
  645. this.loadRealtime(resp, mxUtils.bind(this, function(doc)
  646. {
  647. try
  648. {
  649. // Converts XML files to realtime including old realtime model
  650. if (doc == null || doc.getModel() == null || doc.getModel().getRoot() == null ||
  651. doc.getModel().getRoot().isEmpty() || (doc.getModel().getRoot().has('cells') &&
  652. !doc.getModel().getRoot().has(DriveRealtime.prototype.diagramsKey)))
  653. {
  654. this.getXmlFile(resp, doc, success, error);
  655. }
  656. else
  657. {
  658. // Uses JSON or XML data if flagged
  659. if (doc.getModel().getRoot().has('realtimeConverted'))
  660. {
  661. doc.close();
  662. this.convertRealtimeFile(resp, success, error);
  663. }
  664. else
  665. {
  666. success(new DriveFile(this.ui, null, resp, doc));
  667. }
  668. }
  669. }
  670. catch (e)
  671. {
  672. error(e);
  673. }
  674. }), error);
  675. }
  676. }
  677. }
  678. }
  679. else
  680. {
  681. error({message: mxResources.get('loggedOut')});
  682. }
  683. }), error);
  684. }
  685. };
  686. /**
  687. * Returns true if the given mime type is for Google Realtime files.
  688. */
  689. DriveClient.prototype.isGoogleRealtimeMimeType = function(mimeType)
  690. {
  691. return mimeType != null && mimeType.substring(0, 30) == 'application/vnd.jgraph.mxfile.';
  692. };
  693. /**
  694. * Checks if the client is authorized and calls the next step.
  695. */
  696. DriveClient.prototype.getRealtimeData = function(id, success, error, retryCount)
  697. {
  698. this.executeRequest(gapi.client.drive.realtime.get({'fileId': id,
  699. 'supportsTeamDrives': true}), mxUtils.bind(this, function(resp)
  700. {
  701. var json = (resp.result != null) ? resp.result.data : null;
  702. if (json != null && json.value != null && json.value.diagrams != null)
  703. {
  704. success(json);
  705. }
  706. else if (error != null)
  707. {
  708. error({message: 'realtime.get returned invalid data for ' + id});
  709. }
  710. }), mxUtils.bind(this, function(resp)
  711. {
  712. if (retryCount == null)
  713. {
  714. retryCount = 0;
  715. }
  716. if (retryCount < 3)
  717. {
  718. window.setTimeout(mxUtils.bind(this, function()
  719. {
  720. this.getRealtimeData(id, success, error, retryCount + 1);
  721. }), (retryCount + 1) * 100);
  722. }
  723. else if (error != null)
  724. {
  725. error({message: 'realtime.get failed for ' + id});
  726. }
  727. }));
  728. };
  729. /**
  730. * Checks if the client is authorized and calls the next step.
  731. */
  732. DriveClient.prototype.loadRealtime = function(resp, success, error)
  733. {
  734. // Redirects to new app because the realtime models of different apps are not visible
  735. if (urlParams['ignoremime'] != '1' && this.appId == '420247213240' &&
  736. (resp.mimeType == 'application/vnd.jgraph.mxfile.realtime' ||
  737. resp.mimeType == 'application/mxr'))
  738. {
  739. this.redirectToNewApp(error, resp.id);
  740. }
  741. // Checks if we're in viewer app or if the file is writeable if it needs to be converted
  742. else if (this.appId != '850530949725' && (resp.editable || (resp.mimeType != 'application/mxe' &&
  743. resp.mimeType != 'application/vnd.jgraph.mxfile')) && gapi.drive.realtime != null)
  744. {
  745. var fn = mxUtils.bind(this, function()
  746. {
  747. var acceptResponse = true;
  748. var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  749. {
  750. acceptResponse = false;
  751. error({code: App.ERROR_TIMEOUT, retry: fn});
  752. }), this.ui.timeout);
  753. gapi.drive.realtime.load(resp.id, mxUtils.bind(this, function(doc)
  754. {
  755. window.clearTimeout(timeoutThread);
  756. if (acceptResponse)
  757. {
  758. success(doc);
  759. }
  760. }));
  761. });
  762. fn();
  763. }
  764. // Shows the file as read-only without conversion
  765. else
  766. {
  767. success();
  768. }
  769. };
  770. /**
  771. * Checks if the client is authorized and calls the next step. The ignoreMime argument is
  772. * used for import via getFile. Default is false. The optional
  773. * readLibrary argument is used for reading libraries. Default is false.
  774. */
  775. DriveClient.prototype.getXmlFile = function(resp, doc, success, error, ignoreMime, readLibrary)
  776. {
  777. var token = gapi.auth.getToken().access_token;
  778. var url = resp.downloadUrl + '&access_token=' + token;
  779. // Loads XML to initialize realtime document if realtime is empty
  780. this.ui.loadUrl(url, mxUtils.bind(this, function(data)
  781. {
  782. if (data == null)
  783. {
  784. // TODO: Optional redirect to legacy if link is for old file
  785. error({message: mxResources.get('invalidOrMissingFile')});
  786. }
  787. else if (resp.mimeType == this.libraryMimeType || readLibrary)
  788. {
  789. if (resp.mimeType == this.libraryMimeType && !readLibrary)
  790. {
  791. error({message: mxResources.get('notADiagramFile')});
  792. }
  793. else
  794. {
  795. success(new DriveLibrary(this.ui, data, resp));
  796. }
  797. }
  798. else
  799. {
  800. if (/\.png$/i.test(resp.title))
  801. {
  802. var index = data.lastIndexOf(',');
  803. if (index > 0)
  804. {
  805. var xml = this.ui.extractGraphModelFromPng(data.substring(index + 1));
  806. if (xml != null && xml.length > 0)
  807. {
  808. data = xml;
  809. }
  810. else
  811. {
  812. // Checks if the file contains XML data which can happen when we insert
  813. // the file and then don't post-process it when loaded into the UI which
  814. // is required for creating the images for .PNG and .SVG files.
  815. try
  816. {
  817. var temp = atob(data.substring(index + 1));
  818. if (temp != null && (temp.substring(0, 8) === '<mxfile ' ||
  819. temp.substring(0, 14) === '<mxGraphModel ' ||
  820. temp.substring(0, 14) === '<mxGraphModel>'))
  821. {
  822. data = temp;
  823. }
  824. else
  825. {
  826. // TODO: Import as PNG
  827. }
  828. }
  829. catch (e)
  830. {
  831. // ignore
  832. }
  833. }
  834. }
  835. }
  836. var file = new DriveFile(this.ui, data, resp, doc);
  837. // Checks if mime-type needs to be updated if the file is editable and no viewer app
  838. if (App.GOOGLE_REALTIME && !ignoreMime && this.appId != '850530949725' && file.isEditable() &&
  839. resp.mimeType != this.mimeType && resp.mimeType != this.xmlMimeType)
  840. {
  841. // Overwrites mime-type (only mutable on update when uploading new content)
  842. this.saveFile(file, true, mxUtils.bind(this, function(resp)
  843. {
  844. file.desc = resp;
  845. success(file);
  846. }), error, true);
  847. }
  848. else
  849. {
  850. success(file);
  851. }
  852. }
  853. }), error, (resp.mimeType.substring(0, 6) == 'image/' && resp.mimeType.substring(0, 9) != 'image/svg') ||
  854. /\.png$/i.test(resp.title) || /\.jpe?g$/i.test(resp.title));
  855. };
  856. /**
  857. * Translates this point by the given vector.
  858. *
  859. * @param {number} dx X-coordinate of the translation.
  860. * @param {number} dy Y-coordinate of the translation.
  861. */
  862. DriveClient.prototype.saveFile = function(file, revision, success, error, noCheck, unloading, overwrite, properties)
  863. {
  864. if (file.isEditable())
  865. {
  866. var t0 = new Date().getTime();
  867. noCheck = (noCheck != null) ? noCheck : (!this.ui.isLegacyDriveDomain() || urlParams['ignoremime'] == '1');
  868. // NOTE: Unloading arg is currently ignored, saving during unload/beforeUnload is not possible using
  869. // asynchronous code, which is needed to create the thumbnail, or asynchronous requests which is the only
  870. // way to execute the gapi request below.
  871. // If no thumbnail is created and noCheck is true (which is always true if unloading is true) in which case
  872. // this code is synchronous, the executeRequest call is reached but the request is still not sent. This is
  873. // true for both, calls from beforeUnload and unload handlers. Note sure how to make the call synchronous
  874. // which is said to fix this when called from beforeUnload.
  875. // However, this would result in a missing thumbnail in most cases so a better solution might be to reduce
  876. // the autosave interval in DriveRealtime, but that would increase the number of requests.
  877. unloading = (unloading != null) ? unloading : false;
  878. // Adds optional thumbnail to upload request
  879. var doSave = mxUtils.bind(this, function(thumb, thumbMime, keepExisting)
  880. {
  881. var prevDesc = null;
  882. var pinned = false;
  883. var meta =
  884. {
  885. 'mimeType': file.desc.mimeType,
  886. 'title': file.getTitle()
  887. };
  888. // Overrides old mime type and creates a revision
  889. if (file.realtime == null && this.isGoogleRealtimeMimeType(file.desc.mimeType))
  890. {
  891. prevDesc = file.desc;
  892. meta.mimeType = this.xmlMimeType;
  893. revision = true;
  894. pinned = true;
  895. }
  896. // Inserts a channel ID
  897. if (file.constructor == DriveFile && this.getChannelId(file.desc) == null)
  898. {
  899. if (properties == null)
  900. {
  901. properties = [];
  902. }
  903. properties.push({'key': 'channel', 'value': Editor.guid()});
  904. }
  905. // Specifies that no thumbnail should be uploaded in which case the existing thumbnail is used
  906. if (!keepExisting)
  907. {
  908. // Uses placeholder thumbnail to replace existing one except when unloading
  909. // in which case the XML is updated but the existing thumbnail is not in order
  910. // to avoid executing asynchronous code and get the XML to the server instead
  911. if (thumb == null && !unloading)
  912. {
  913. thumb = this.placeholderThumbnail;
  914. thumbMime = this.placeholderMimeType;
  915. }
  916. // Adds metadata for thumbnail
  917. if (thumb != null && thumbMime != null)
  918. {
  919. meta.thumbnail =
  920. {
  921. 'image': thumb,
  922. 'mimeType': thumbMime
  923. };
  924. }
  925. }
  926. // Updates saveDelay on drive file
  927. var wrapper = mxUtils.bind(this, function()
  928. {
  929. file.saveDelay = new Date().getTime() - t0;
  930. success.apply(this, arguments);
  931. if (prevDesc != null)
  932. {
  933. // Pins previous revision
  934. this.executeRequest(gapi.client.drive.revisions.get(
  935. {
  936. 'fileId': prevDesc.id,
  937. 'revisionId': prevDesc.headRevisionId,
  938. 'supportsTeamDrives': true
  939. }), mxUtils.bind(this, mxUtils.bind(this, function(resp)
  940. {
  941. resp.pinned = true;
  942. this.executeRequest(gapi.client.drive.revisions.update(
  943. {
  944. 'fileId': prevDesc.id,
  945. 'revisionId': prevDesc.headRevisionId,
  946. 'resource': resp
  947. }));
  948. })));
  949. // Logs conversion
  950. this.ui.logEvent({category: 'RT-CONVERT',
  951. action: 'from-' + prevDesc.id + '.' +
  952. prevDesc.headRevisionId + '-to-' +
  953. file.desc.id + '.' + file.desc.headRevisionId + '-' +
  954. file.convertedFrom,
  955. label: (this.user != null) ? this.user.id : 'unknown-user'});
  956. }
  957. });
  958. var doExecuteRequest = mxUtils.bind(this, function(data, binary)
  959. {
  960. if (properties != null)
  961. {
  962. meta.properties = properties;
  963. }
  964. // Used to check if file was changed externally
  965. var etag = (!overwrite && file.constructor == DriveFile &&
  966. file.realtime == null) ? file.desc.etag : null;
  967. this.executeRequest(this.createUploadRequest(file.getId(), meta,
  968. data, revision || (file.desc.mimeType != this.xmlMimeType &&
  969. file.desc.mimeType != this.mimeType && file.desc.mimeType !=
  970. this.libraryMimeType), binary, etag, pinned), wrapper, error);
  971. });
  972. if (this.ui.useCanvasForExport && /(\.png)$/i.test(file.getTitle()))
  973. {
  974. this.ui.getEmbeddedPng(mxUtils.bind(this, function(data)
  975. {
  976. doExecuteRequest(data, true);
  977. }), error, (this.ui.getCurrentFile() != file) ? file.getData() : null);
  978. }
  979. else
  980. {
  981. doExecuteRequest(file.getData(), false);
  982. }
  983. });
  984. // Indirection to generate thumbnails if enabled and supported
  985. // (required because generation of thumbnails is asynchronous)
  986. var fn = mxUtils.bind(this, function()
  987. {
  988. // NOTE: getThumbnail is asynchronous and returns false if no thumbnails can be created
  989. if (unloading || file.constructor == DriveLibrary || !this.enableThumbnails || urlParams['thumb'] == '0' ||
  990. (file.realtime != null && !file.realtime.connected) || !this.ui.getThumbnail(this.thumbnailWidth,
  991. mxUtils.bind(this, function(canvas)
  992. {
  993. // Callback for getThumbnail
  994. var thumb = null;
  995. if (canvas != null)
  996. {
  997. try
  998. {
  999. // Security errors are possible
  1000. thumb = canvas.toDataURL('image/png');
  1001. }
  1002. catch (e)
  1003. {
  1004. // ignore and continue with placeholder
  1005. }
  1006. }
  1007. // Maximum thumbnail size is 2MB
  1008. if (thumb == null || thumb.length > this.maxThumbnailSize)
  1009. {
  1010. thumb = null;
  1011. }
  1012. else
  1013. {
  1014. // Converts base64 data into required format for Drive (base64url with no prefix)
  1015. thumb = thumb.substring(thumb.indexOf(',') + 1).replace(/\+/g, '-').replace(/\//g, '_');
  1016. }
  1017. doSave(thumb, 'image/png');
  1018. })))
  1019. {
  1020. // If-branch
  1021. doSave(null, null, file.constructor != DriveLibrary && (file.realtime == null || file.realtime.connected));
  1022. }
  1023. });
  1024. // New revision is required if mime type changes, but the mime type should not be replaced
  1025. // if the file has been converted to the new realtime format. To check this we make sure
  1026. // that the mime type has not changed before updating it in the case of the legacy app.
  1027. // Note: We need to always check the mime type because saveFile cancels previous save
  1028. // attempts so if the save frequency is higher than the time for all retries than you
  1029. // will never see the error message and accumulate lots of changes that will be lost.
  1030. if (noCheck || !revision)
  1031. {
  1032. fn();
  1033. }
  1034. else
  1035. {
  1036. this.verifyMimeType(file.getId(), fn, true);
  1037. }
  1038. }
  1039. else
  1040. {
  1041. this.ui.editor.graph.reset();
  1042. if (error != null)
  1043. {
  1044. error({message: mxResources.get('readOnly')});
  1045. }
  1046. }
  1047. };
  1048. /**
  1049. * Sends a message to all collaborators and stores the head revision ID.
  1050. */
  1051. DriveClient.prototype.notifyRealtimeConverted = function(desc)
  1052. {
  1053. try
  1054. {
  1055. if (gapi.drive.realtime != null)
  1056. {
  1057. gapi.drive.realtime.load(desc.id, mxUtils.bind(this, function(doc)
  1058. {
  1059. try
  1060. {
  1061. if (doc != null && doc.getModel() != null &&
  1062. doc.getModel().getRoot() != null)
  1063. {
  1064. doc.getModel().getRoot().set('realtimeConverted',
  1065. desc.headRevisionId);
  1066. }
  1067. }
  1068. catch (e)
  1069. {
  1070. // ignore
  1071. }
  1072. }));
  1073. }
  1074. }
  1075. catch (e)
  1076. {
  1077. // ignore
  1078. }
  1079. };
  1080. /**
  1081. * Verifies the mime type of the given file ID.
  1082. */
  1083. DriveClient.prototype.verifyMimeType = function(fileId, fn, force, error)
  1084. {
  1085. if (this.lastMimeCheck == null)
  1086. {
  1087. this.lastMimeCheck = 0;
  1088. }
  1089. var now = new Date().getTime();
  1090. if (force || now - this.lastMimeCheck > this.mimeTypeCheckCoolOff)
  1091. {
  1092. this.lastMimeCheck = now;
  1093. if (!this.checkingMimeType)
  1094. {
  1095. this.checkingMimeType = true;
  1096. this.executeRequest(gapi.client.drive.files.get({'fileId': fileId, 'fields': 'mimeType', 'supportsTeamDrives': true}), mxUtils.bind(this, function(resp)
  1097. {
  1098. this.checkingMimeType = false;
  1099. if (resp != null && resp.mimeType == 'application/vnd.jgraph.mxfile.realtime')
  1100. {
  1101. this.redirectToNewApp(error, fileId);
  1102. }
  1103. else if (fn != null)
  1104. {
  1105. fn();
  1106. }
  1107. }));
  1108. }
  1109. }
  1110. };
  1111. /**
  1112. * Checks if the client is authorized and calls the next step.
  1113. */
  1114. DriveClient.prototype.redirectToNewApp = function(error, fileId)
  1115. {
  1116. this.ui.spinner.stop();
  1117. if (!this.redirectDialogShowing)
  1118. {
  1119. this.redirectDialogShowing = true;
  1120. var url = window.location.protocol + '//' + this.newAppHostname + '/' + this.ui.getSearch(
  1121. ['create', 'title', 'mode', 'url', 'drive', 'splash', 'state']) + '#G' + fileId;
  1122. if (error != null)
  1123. {
  1124. this.ui.confirm(mxResources.get('redirectToNewApp'), mxUtils.bind(this, function()
  1125. {
  1126. this.redirectDialogShowing = false;
  1127. window.location.href = url;
  1128. }), mxUtils.bind(this, function()
  1129. {
  1130. this.redirectDialogShowing = false;
  1131. if (error != null)
  1132. {
  1133. error();
  1134. }
  1135. }));
  1136. }
  1137. else
  1138. {
  1139. this.ui.alert(mxResources.get('redirectToNewApp'), mxUtils.bind(this, function()
  1140. {
  1141. this.redirectDialogShowing = false;
  1142. window.location.href = url;
  1143. }));
  1144. }
  1145. }
  1146. };
  1147. /**
  1148. * Translates this point by the given vector.
  1149. *
  1150. * @param {number} dx X-coordinate of the translation.
  1151. * @param {number} dy Y-coordinate of the translation.
  1152. */
  1153. DriveClient.prototype.insertFile = function(title, data, folderId, success, error, mimeType, binary, allowRealtime)
  1154. {
  1155. mimeType = (mimeType != null) ? mimeType : ((App.GOOGLE_REALTIME) ? this.mimeType : this.xmlMimeType);
  1156. allowRealtime = (allowRealtime != null) ? allowRealtime : true;
  1157. var metadata =
  1158. {
  1159. 'mimeType': mimeType,
  1160. 'title': title
  1161. };
  1162. if (folderId != null)
  1163. {
  1164. metadata.parents = [{'kind': 'drive#fileLink', 'id': folderId}];
  1165. }
  1166. // NOTE: Cannot create thumbnail on insert since no ui has no current file
  1167. this.executeRequest(this.createUploadRequest(null, metadata, data, false, binary), mxUtils.bind(this, function(resp)
  1168. {
  1169. if (mimeType == this.libraryMimeType)
  1170. {
  1171. success(new DriveLibrary(this.ui, data, resp));
  1172. }
  1173. else if (resp == false)
  1174. {
  1175. if (error != null)
  1176. {
  1177. error({message: mxResources.get('errorSavingFile')});
  1178. }
  1179. }
  1180. else if (App.GOOGLE_REALTIME && allowRealtime &&
  1181. this.isGoogleRealtimeMimeType(resp.mimeType))
  1182. {
  1183. this.loadRealtime(resp, mxUtils.bind(this, function(doc)
  1184. {
  1185. if (this.user != null)
  1186. {
  1187. var file = new DriveFile(this.ui, data, resp, doc);
  1188. // Avoids creating a new revision on first autosave of new files
  1189. file.lastAutosaveRevision = new Date().getTime();
  1190. success(file);
  1191. }
  1192. else if (error != null)
  1193. {
  1194. error({message: mxResources.get('loggedOut')});
  1195. }
  1196. }), error, false);
  1197. }
  1198. else
  1199. {
  1200. success(new DriveFile(this.ui, data, resp));
  1201. }
  1202. }), error);
  1203. };
  1204. /**
  1205. * Translates this point by the given vector.
  1206. *
  1207. * @param {number} dx X-coordinate of the translation.
  1208. * @param {number} dy Y-coordinate of the translation.
  1209. */
  1210. DriveClient.prototype.createUploadRequest = function(id, metadata, data, revision, binary, etag, pinned)
  1211. {
  1212. binary = (binary != null) ? binary : false;
  1213. var bd = '-------314159265358979323846';
  1214. var delim = '\r\n--' + bd + '\r\n';
  1215. var close = '\r\n--' + bd + '--';
  1216. var ctype = 'application/octect-stream';
  1217. var headers = {'Content-Type' : 'multipart/mixed; boundary="' + bd + '"'};
  1218. if (etag != null)
  1219. {
  1220. headers['If-Match'] = etag;
  1221. }
  1222. var reqObj =
  1223. {
  1224. 'path': '/upload/drive/v2/files' + (id != null ? '/' + id : ''),
  1225. 'method': (id != null) ? 'PUT' : 'POST',
  1226. 'params': {'uploadType': 'multipart'},
  1227. 'headers': headers,
  1228. 'body' : delim + 'Content-Type: application/json\r\n\r\n' + JSON.stringify(metadata) + delim +
  1229. 'Content-Type: ' + ctype + '\r\n' + 'Content-Transfer-Encoding: base64\r\n' + '\r\n' +
  1230. ((data != null) ? (binary) ? data : Base64.encode(data) : '') + close
  1231. }
  1232. if (!revision)
  1233. {
  1234. reqObj.params['newRevision'] = false;
  1235. }
  1236. if (pinned)
  1237. {
  1238. reqObj.params['pinned'] = true;
  1239. }
  1240. reqObj.params['supportsTeamDrives'] = true;
  1241. reqObj.params['fields'] = this.allFields;
  1242. return gapi.client.request(reqObj);
  1243. };
  1244. /**
  1245. * Translates this point by the given vector.
  1246. *
  1247. * @param {number} dx X-coordinate of the translation.
  1248. * @param {number} dy Y-coordinate of the translation.
  1249. */
  1250. DriveClient.prototype.pickFile = function(fn, acceptAllFiles)
  1251. {
  1252. this.filePickerCallback = (fn != null) ? fn : mxUtils.bind(this, function(id)
  1253. {
  1254. this.ui.loadFile('G' + id);
  1255. });
  1256. this.filePicked = mxUtils.bind(this, function(data)
  1257. {
  1258. if (data.action == google.picker.Action.PICKED)
  1259. {
  1260. this.filePickerCallback(data.docs[0].id);
  1261. }
  1262. });
  1263. if (this.ui.spinner.spin(document.body, mxResources.get('authorizing')))
  1264. {
  1265. this.execute(mxUtils.bind(this, function()
  1266. {
  1267. this.ui.spinner.stop();
  1268. // Reuses picker as long as token doesn't change.
  1269. var token = gapi.auth.getToken().access_token;
  1270. var name = (acceptAllFiles) ? 'genericPicker' : 'filePicker';
  1271. // Click on background closes dialog as workaround for blocking dialog
  1272. // states such as 401 where the dialog cannot be closed and blocks UI
  1273. var exit = mxUtils.bind(this, function(evt)
  1274. {
  1275. // Workaround for click from appIcon on second call
  1276. if (mxEvent.getSource(evt).className == 'picker modal-dialog-bg picker-dialog-bg')
  1277. {
  1278. mxEvent.removeListener(document, 'click', exit);
  1279. this[name].setVisible(false);
  1280. }
  1281. });
  1282. if (this[name] == null || this[name + 'Token'] != token)
  1283. {
  1284. // FIXME: Dispose not working
  1285. // if (this[name] != null)
  1286. // {
  1287. // console.log(name, this[name]);
  1288. // this[name].dispose();
  1289. // }
  1290. this[name + 'Token'] = token;
  1291. // Pseudo-hierarchical directory view, see
  1292. // https://groups.google.com/forum/#!topic/google-picker-api/FSFcuJe7icQ
  1293. var view = new google.picker.DocsView(google.picker.ViewId.FOLDERS)
  1294. .setParent('root')
  1295. .setIncludeFolders(true);
  1296. var view2 = new google.picker.DocsView()
  1297. .setIncludeFolders(true);
  1298. var view3 = new google.picker.DocsView()
  1299. .setEnableTeamDrives(true)
  1300. .setIncludeFolders(true);
  1301. var view4 = new google.picker.DocsUploadView()
  1302. .setIncludeFolders(true);
  1303. if (!acceptAllFiles)
  1304. {
  1305. view.setMimeTypes(this.mimeTypes);
  1306. view2.setMimeTypes(this.mimeTypes);
  1307. view3.setMimeTypes(this.mimeTypes);
  1308. }
  1309. else
  1310. {
  1311. view.setMimeTypes('*/*');
  1312. view2.setMimeTypes('*/*');
  1313. view3.setMimeTypes('*/*');
  1314. }
  1315. this[name] = new google.picker.PickerBuilder()
  1316. .setOAuthToken(this[name + 'Token'])
  1317. .setLocale(mxLanguage)
  1318. .setAppId(this.appId)
  1319. .enableFeature(google.picker.Feature.SUPPORT_TEAM_DRIVES)
  1320. .addView(view)
  1321. .addView(view2)
  1322. .addView(view3)
  1323. .addView(google.picker.ViewId.RECENTLY_PICKED)
  1324. .addView(view4)
  1325. .setCallback(mxUtils.bind(this, function(data)
  1326. {
  1327. if (data.action == google.picker.Action.PICKED ||
  1328. data.action == google.picker.Action.CANCEL)
  1329. {
  1330. mxEvent.removeListener(document, 'click', exit);
  1331. }
  1332. if (data.action == google.picker.Action.PICKED)
  1333. {
  1334. this.filePicked(data);
  1335. }
  1336. })).build();
  1337. }
  1338. mxEvent.addListener(document, 'click', exit);
  1339. this[name].setVisible(true);
  1340. }));
  1341. }
  1342. };
  1343. /**
  1344. * Translates this point by the given vector.
  1345. *
  1346. * @param {number} dx X-coordinate of the translation.
  1347. * @param {number} dy Y-coordinate of the translation.
  1348. */
  1349. DriveClient.prototype.pickFolder = function(fn)
  1350. {
  1351. this.folderPickerCallback = fn;
  1352. // Picker is initialized once and points to this function
  1353. // which is overridden each time to the picker is shown
  1354. var showPicker = mxUtils.bind(this, function()
  1355. {
  1356. if (this.ui.spinner.spin(document.body, mxResources.get('authorizing')))
  1357. {
  1358. this.execute(mxUtils.bind(this, function()
  1359. {
  1360. this.ui.spinner.stop();
  1361. // Reuses picker as long as token doesn't change.
  1362. var token = gapi.auth.getToken().access_token;
  1363. var name = 'folderPicker';
  1364. // Click on background closes dialog as workaround for blocking dialog
  1365. // states such as 401 where the dialog cannot be closed and blocks UI
  1366. var exit = mxUtils.bind(this, function(evt)
  1367. {
  1368. // Workaround for click from appIcon on second call
  1369. if (mxEvent.getSource(evt).className == 'picker modal-dialog-bg picker-dialog-bg')
  1370. {
  1371. mxEvent.removeListener(document, 'click', exit);
  1372. this[name].setVisible(false);
  1373. }
  1374. });
  1375. if (this[name] == null || this[name + 'Token'] != token)
  1376. {
  1377. // FIXME: Dispose not working
  1378. // if (this[name] != null)
  1379. // {
  1380. // console.log(name, this[name]);
  1381. // this[name].dispose();
  1382. // }
  1383. this[name + 'Token'] = token;
  1384. // Pseudo-hierarchical directory view, see
  1385. // https://groups.google.com/forum/#!topic/google-picker-api/FSFcuJe7icQ
  1386. var view = new google.picker.DocsView(google.picker.ViewId.FOLDERS)
  1387. .setParent('root')
  1388. .setIncludeFolders(true)
  1389. .setSelectFolderEnabled(true)
  1390. .setMimeTypes('application/vnd.google-apps.folder');
  1391. var view2 = new google.picker.DocsView()
  1392. .setIncludeFolders(true)
  1393. .setSelectFolderEnabled(true)
  1394. .setMimeTypes('application/vnd.google-apps.folder');
  1395. var view3 = new google.picker.DocsView()
  1396. .setIncludeFolders(true)
  1397. .setEnableTeamDrives(true)
  1398. .setSelectFolderEnabled(true)
  1399. .setMimeTypes('application/vnd.google-apps.folder');
  1400. this[name] = new google.picker.PickerBuilder()
  1401. .setSelectableMimeTypes('application/vnd.google-apps.folder')
  1402. .setOAuthToken(this[name + 'Token'])
  1403. .setLocale(mxLanguage)
  1404. .setAppId(this.appId)
  1405. .enableFeature(google.picker.Feature.SUPPORT_TEAM_DRIVES)
  1406. .addView(view)
  1407. .addView(view2)
  1408. .addView(view3)
  1409. .addView(google.picker.ViewId.RECENTLY_PICKED)
  1410. .setTitle(mxResources.get('pickFolder'))
  1411. .setCallback(mxUtils.bind(this, function(data)
  1412. {
  1413. if (data.action == google.picker.Action.PICKED ||
  1414. data.action == google.picker.Action.CANCEL)
  1415. {
  1416. mxEvent.removeListener(document, 'click', exit);
  1417. }
  1418. this.folderPickerCallback(data);
  1419. })).build();
  1420. }
  1421. mxEvent.addListener(document, 'click', exit);
  1422. this[name].setVisible(true);
  1423. }));
  1424. }
  1425. });
  1426. this.ui.confirm(mxResources.get('useRootFolder'), mxUtils.bind(this, function()
  1427. {
  1428. this.folderPickerCallback({action: google.picker.Action.PICKED,
  1429. docs: [{type: 'folder', id: 'root'}]});
  1430. }), mxUtils.bind(this, function()
  1431. {
  1432. showPicker();
  1433. }), mxResources.get('yes'), mxResources.get('no'));
  1434. };
  1435. /**
  1436. * Translates this point by the given vector.
  1437. *
  1438. * @param {number} dx X-coordinate of the translation.
  1439. * @param {number} dy Y-coordinate of the translation.
  1440. */
  1441. DriveClient.prototype.pickLibrary = function(fn)
  1442. {
  1443. this.filePickerCallback = fn;
  1444. this.filePicked = mxUtils.bind(this, function(data)
  1445. {
  1446. if (data.action == google.picker.Action.PICKED)
  1447. {
  1448. this.filePickerCallback(data.docs[0].id);
  1449. }
  1450. else if (data.action == google.picker.Action.CANCEL && this.ui.getCurrentFile() == null)
  1451. {
  1452. this.ui.showSplash();
  1453. }
  1454. });
  1455. if (this.ui.spinner.spin(document.body, mxResources.get('authorizing')))
  1456. {
  1457. this.execute(mxUtils.bind(this, function()
  1458. {
  1459. this.ui.spinner.stop();
  1460. // Click on background closes dialog as workaround for blocking dialog
  1461. // states such as 401 where the dialog cannot be closed and blocks UI
  1462. var exit = mxUtils.bind(this, function(evt)
  1463. {
  1464. // Workaround for click from appIcon on second call
  1465. if (mxEvent.getSource(evt).className == 'picker modal-dialog-bg picker-dialog-bg')
  1466. {
  1467. mxEvent.removeListener(document, 'click', exit);
  1468. this.libraryPicker.setVisible(false);
  1469. }
  1470. });
  1471. // Reuses picker as long as token doesn't change
  1472. var token = gapi.auth.getToken().access_token;
  1473. if (this.libraryPicker == null || this.libraryPickerToken != token)
  1474. {
  1475. // FIXME: Dispose not working
  1476. // if (this[name] != null)
  1477. // {
  1478. // console.log(name, this[name]);
  1479. // this[name].dispose();
  1480. // }
  1481. this.libraryPickerToken = token;
  1482. // Pseudo-hierarchical directory view, see
  1483. // https://groups.google.com/forum/#!topic/google-picker-api/FSFcuJe7icQ
  1484. var view = new google.picker.DocsView(google.picker.ViewId.FOLDERS)
  1485. .setParent('root')
  1486. .setIncludeFolders(true)
  1487. .setMimeTypes(this.libraryMimeType + ',application/xml,text/plain,application/octet-stream');
  1488. var view2 = new google.picker.DocsView()
  1489. .setIncludeFolders(true)
  1490. .setMimeTypes(this.libraryMimeType + ',application/xml,text/plain,application/octet-stream');
  1491. var view3 = new google.picker.DocsView()
  1492. .setEnableTeamDrives(true)
  1493. .setIncludeFolders(true)
  1494. .setMimeTypes(this.libraryMimeType + ',application/xml,text/plain,application/octet-stream');
  1495. var view4 = new google.picker.DocsUploadView()
  1496. .setIncludeFolders(true);
  1497. this.libraryPicker = new google.picker.PickerBuilder()
  1498. .setOAuthToken(this.libraryPickerToken)
  1499. .setLocale(mxLanguage)
  1500. .setAppId(this.appId)
  1501. .enableFeature(google.picker.Feature.SUPPORT_TEAM_DRIVES)
  1502. .addView(view)
  1503. .addView(view2)
  1504. .addView(view3)
  1505. .addView(google.picker.ViewId.RECENTLY_PICKED)
  1506. .addView(view4)
  1507. .setCallback(mxUtils.bind(this, function(data)
  1508. {
  1509. if (data.action == google.picker.Action.PICKED ||
  1510. data.action == google.picker.Action.CANCEL)
  1511. {
  1512. mxEvent.removeListener(document, 'click', exit);
  1513. }
  1514. if (data.action == google.picker.Action.PICKED)
  1515. {
  1516. this.filePicked(data);
  1517. }
  1518. })).build();
  1519. }
  1520. mxEvent.addListener(document, 'click', exit);
  1521. this.libraryPicker.setVisible(true);
  1522. }));
  1523. }
  1524. };
  1525. /**
  1526. * Translates this point by the given vector.
  1527. *
  1528. * @param {number} dx X-coordinate of the translation.
  1529. * @param {number} dy Y-coordinate of the translation.
  1530. */
  1531. DriveClient.prototype.showPermissions = function(id)
  1532. {
  1533. this.checkToken(mxUtils.bind(this, function()
  1534. {
  1535. var shareClient = new gapi.drive.share.ShareClient(this.appId);
  1536. shareClient.setOAuthToken(gapi.auth.getToken().access_token);
  1537. shareClient.setItemIds([id]);
  1538. shareClient.showSettingsDialog();
  1539. }));
  1540. };
  1541. /**
  1542. * Converts the given file from realtime to XML.
  1543. */
  1544. DriveClient.prototype.getRealtimeAge = function(desc, json)
  1545. {
  1546. var mod = (json != null && json.value != null && json.value.modifiedDate != null) ?
  1547. json.value.modifiedDate.json : null;
  1548. var result = 0;
  1549. if (mod != null && mod > 0)
  1550. {
  1551. var ts = new Date(desc.modifiedDate);
  1552. var rt = new Date(mod);
  1553. result = ts.getTime() - rt.getTime();
  1554. }
  1555. return result;
  1556. };
  1557. /**
  1558. * Converts the given file from realtime to XML.
  1559. */
  1560. DriveClient.prototype.convertRealtimeFile = function(desc, success, error)
  1561. {
  1562. var xmlSuccess = mxUtils.bind(this, function(file)
  1563. {
  1564. file.convertedFrom = 'xml';
  1565. success(file);
  1566. });
  1567. var jsonSuccess = mxUtils.bind(this, function(file)
  1568. {
  1569. file.convertedFrom = 'json';
  1570. success(file);
  1571. });
  1572. this.getRealtimeData(desc.id, mxUtils.bind(this, function(json)
  1573. {
  1574. try
  1575. {
  1576. var age = this.getRealtimeAge(desc, json);
  1577. this.notifyRealtimeConverted(desc);
  1578. // Uses realtime if newer or less than 5 minutes old
  1579. if (age < 300000)
  1580. {
  1581. jsonSuccess(new DriveFile(this.ui, mxUtils.getXml(
  1582. this.convertJsonToXml(json)), desc));
  1583. }
  1584. else
  1585. {
  1586. this.getXmlFile(desc, null, xmlSuccess, mxUtils.bind(this, function()
  1587. {
  1588. try
  1589. {
  1590. jsonSuccess(new DriveFile(this.ui, mxUtils.getXml(
  1591. this.convertJsonToXml(json)), desc));
  1592. }
  1593. catch (e)
  1594. {
  1595. this.getXmlFile(desc, null, xmlSuccess, error);
  1596. }
  1597. }));
  1598. }
  1599. }
  1600. catch (e)
  1601. {
  1602. this.getXmlFile(desc, null, xmlSuccess, error);
  1603. }
  1604. }), mxUtils.bind(this, function()
  1605. {
  1606. this.getXmlFile(desc, null, xmlSuccess, error);
  1607. }));
  1608. };
  1609. /**
  1610. * Returns the location as a new object.
  1611. */
  1612. DriveClient.prototype.convertJsonToXml = function(json, uncompressed)
  1613. {
  1614. if (json.value == null || json.value.diagrams == null)
  1615. {
  1616. throw Error('Invalid JSON: no diagrams in root map');
  1617. }
  1618. else
  1619. {
  1620. var node = mxUtils.createXmlDocument().createElement('mxfile');
  1621. var diagrams = json.value.diagrams.value;
  1622. for (var i = 0; i < diagrams.length; i++)
  1623. {
  1624. try
  1625. {
  1626. var diagramNode = this.decodeJsonPage(diagrams[i].value,
  1627. node.ownerDocument.createElement('diagram'),
  1628. uncompressed);
  1629. //if (diagramNode.getAttribute('name') == null)
  1630. //{
  1631. // TODO: Should only use when converting but not when comparing
  1632. //diagramNode.setAttribute('name', mxResources.get('pageWithNumber', [i + 1]));
  1633. //}
  1634. node.appendChild(diagramNode);
  1635. }
  1636. catch (e)
  1637. {
  1638. throw Error('Error on page ' + i + ': ' + e.stack);
  1639. }
  1640. }
  1641. //console.log('leaving convertJson', mxUtils.getPrettyXml(node));
  1642. return node;
  1643. }
  1644. };
  1645. /**
  1646. * Returns true if copy, export and print are not allowed for this file.
  1647. */
  1648. DriveClient.prototype.decodeJsonPage = function(json, node, uncompressed)
  1649. {
  1650. if (json == null)
  1651. {
  1652. throw Error('Invalid JSON: json for page is null');
  1653. }
  1654. else
  1655. {
  1656. var codec = new mxCodec();
  1657. var root = this.createJsonCell(json.root, codec);
  1658. if (root == null)
  1659. {
  1660. throw Error('Invalid JSON: no root cell for page');
  1661. }
  1662. else
  1663. {
  1664. // Dummy model for encoding
  1665. var modelNode = codec.encode(new mxGraphModel(root));
  1666. this.decodeJsonViewState(json, modelNode);
  1667. if (uncompressed)
  1668. {
  1669. node.appendChild(modelNode);
  1670. }
  1671. else
  1672. {
  1673. mxUtils.setTextContent(node, this.ui.editor.graph.compressNode(modelNode));
  1674. }
  1675. // Adds attributes to diagram node
  1676. if (json.id != null)
  1677. {
  1678. node.setAttribute('id', json.id.json);
  1679. }
  1680. else
  1681. {
  1682. // Workaround for missing page ID in JSON
  1683. node.setAttribute('id', Editor.guid());
  1684. }
  1685. if (json.name != null)
  1686. {
  1687. node.setAttribute('name', json.name.json);
  1688. }
  1689. }
  1690. }
  1691. //console.log('decoded json page', json, node);
  1692. return node;
  1693. };
  1694. /**
  1695. * Writes the view state to the given node.
  1696. */
  1697. DriveClient.prototype.decodeJsonViewState = function(json, node)
  1698. {
  1699. // Page format is stored as "width,height"
  1700. var pf = (json.pageFormat != null) ? json.pageFormat.json : null;
  1701. if (pf != null && pf.length > 0)
  1702. {
  1703. var values = pf.split(',');
  1704. if (values.length > 1)
  1705. {
  1706. node.setAttribute('pageWidth', values[0]);
  1707. node.setAttribute('pageHeight', values[1]);
  1708. }
  1709. }
  1710. var bg = (json.backgroundColor != null) ? json.backgroundColor.json : null;
  1711. if (bg != null && bg.length > 0)
  1712. {
  1713. node.setAttribute('background', bg);
  1714. }
  1715. var img = (json.backgroundImage != null) ? json.backgroundImage.json : null;
  1716. if (img != null && img.length > 0)
  1717. {
  1718. node.setAttribute('backgroundImage', img);
  1719. }
  1720. node.setAttribute('fold', (json.foldingEnabled != null) ? json.foldingEnabled.json : '0');
  1721. node.setAttribute('pageScale', (json.pageScale != null) ? json.pageScale.json : mxGraph.prototype.pageScale);
  1722. node.setAttribute('math', (json.mathEnabled != null) ? json.mathEnabled.json : '0');
  1723. node.setAttribute('shadow', (json.shadowVisible != null) ? json.shadowVisible.json : '0');
  1724. return node;
  1725. };
  1726. /**
  1727. * Syncs initial state from collab model to graph model.
  1728. */
  1729. DriveClient.prototype.createJsonCell = function(json, codec)
  1730. {
  1731. if (json != null && json.id != null)
  1732. {
  1733. var val = json.value;
  1734. var cell = this.jsonToCell(val, codec);
  1735. codec.putObject(json.id, cell);
  1736. cell.source = (val.source != null) ? this.createJsonCell(val.source, codec) : null;
  1737. cell.target = (val.target != null) ? this.createJsonCell(val.target, codec) : null;
  1738. // Cells can be serialized as parents of terminals
  1739. this.createJsonCell(val.parent, codec)
  1740. for (var i = 0; i < val.children.value.length; i++)
  1741. {
  1742. var child = this.createJsonCell(val.children.value[i], codec);
  1743. if (child != null)
  1744. {
  1745. cell.insert(child);
  1746. }
  1747. else
  1748. {
  1749. throw Error('Invalid JSON: no child ' + i + ' for cell ' + json.id);
  1750. }
  1751. }
  1752. return cell;
  1753. }
  1754. else if (json != null && json.ref != null)
  1755. {
  1756. return codec.objects[json.ref];
  1757. }
  1758. else
  1759. {
  1760. return null;
  1761. }
  1762. };
  1763. /**
  1764. * Adds the listener for automatically saving the diagram for local changes.
  1765. */
  1766. DriveClient.prototype.jsonToCell = function(val, codec)
  1767. {
  1768. var cell = new mxCell();
  1769. cell.id = val.cellId.json;
  1770. cell.vertex = val.type.json == 'vertex';
  1771. cell.edge = val.type.json == 'edge';
  1772. cell.connectable = val.connectable.json != '0';
  1773. cell.collapsed = val.collapsed.json == '1';
  1774. cell.visible = val.visible.json != '0';
  1775. cell.style = (val.style != null) ? val.style.json : null;
  1776. cell.value = (val.xmlValue != null) ?
  1777. mxUtils.parseXml(val.xmlValue.json).documentElement :
  1778. ((val.value != null) ? val.value.json : null);
  1779. cell.geometry = (val.geometry != null) ?
  1780. codec.decode(mxUtils.parseXml(val.geometry.json).documentElement) : null;
  1781. return cell;
  1782. };