DriveClient.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  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. if (this.ui.editor.chromeless && urlParams['rt'] != '1')
  13. {
  14. this.appId = '850530949725';
  15. this.clientId = '850530949725.apps.googleusercontent.com';
  16. this.scopes = ['https://www.googleapis.com/auth/drive.readonly', 'openid'];
  17. // Only used for writing files which is disabled in viewer app
  18. this.mimeType = 'all_types_supported';
  19. }
  20. else if (this.ui.isDriveDomain())
  21. {
  22. this.appId = '671128082532';
  23. this.clientId = '671128082532.apps.googleusercontent.com';
  24. this.mimeType = 'application/vnd.jgraph.mxfile.realtime';
  25. }
  26. else
  27. {
  28. // Uses a different mime-type and realtime model than the drive domain
  29. // because realtime models for different app IDs are not compatible
  30. this.appId = '420247213240';
  31. this.clientId = '420247213240-hnbju1pt13seqrc1hhd5htpotk4g9q7u.apps.googleusercontent.com';
  32. this.mimeType = 'application/vnd.jgraph.mxfile.rtlegacy';
  33. }
  34. this.mimeTypes = 'application/mxe,application/vnd.jgraph.mxfile,' +
  35. 'application/mxr,application/vnd.jgraph.mxfile.realtime,' +
  36. 'application/vnd.jgraph.mxfile.rtlegacy';
  37. };
  38. // Extends mxEventSource
  39. mxUtils.extend(DriveClient, mxEventSource);
  40. /**
  41. * OAuth 2.0 scopes for installing Drive Apps.
  42. */
  43. DriveClient.prototype.scopes = (urlParams['photos'] == '1') ?
  44. ['https://www.googleapis.com/auth/drive.file',
  45. 'https://www.googleapis.com/auth/drive.install',
  46. 'https://www.googleapis.com/auth/photos',
  47. 'https://www.googleapis.com/auth/photos.upload',
  48. 'https://www.googleapis.com/auth/userinfo.profile'] :
  49. ['https://www.googleapis.com/auth/drive.file',
  50. 'https://www.googleapis.com/auth/drive.install',
  51. 'https://www.googleapis.com/auth/userinfo.profile'];
  52. /**
  53. * Specifies if thumbnails should be enabled. Default is true.
  54. * LATER: If thumbnails are disabled, make sure to replace the
  55. * existing thumbnail with the placeholder only once.
  56. */
  57. DriveClient.prototype.enableThumbnails = true;
  58. /**
  59. * Specifies the width for thumbnails. Default is 480. This value
  60. * must be between 220 and 1600.
  61. */
  62. DriveClient.prototype.thumbnailWidth = 480;
  63. /**
  64. * The maximum number of bytes per thumbnail. Default is 2000000.
  65. */
  66. DriveClient.prototype.maxThumbnailSize = 2000000;
  67. /**
  68. * Defines the base64url PNG to be used if no thumbnail was generated
  69. * (including the case where thumbnails are disabled).
  70. */
  71. 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+LDGyvXE2kmO2Q1Lq17RSd6ND48QIwFVuLNHTOPbEpTOz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'.replace(/\+/g, '-').replace(/\//g, '_');
  72. /**
  73. * Mime type for the paceholder thumbnail.
  74. */
  75. DriveClient.prototype.placeholderMimeType = 'image/png';
  76. /**
  77. * Executes the first step for connecting to Google Drive.
  78. */
  79. DriveClient.prototype.libraryMimeType = 'application/vnd.jgraph.mxlibrary';
  80. /**
  81. * Contains the hostname of the new app.
  82. */
  83. DriveClient.prototype.newAppHostname = 'www.draw.io';
  84. /**
  85. * Contains the hostname of the old app.
  86. */
  87. DriveClient.prototype.oldAppHostname = 'legacy.draw.io';
  88. /**
  89. * Executes the first step for connecting to Google Drive.
  90. */
  91. DriveClient.prototype.extension = '.html';
  92. /**
  93. * Interval for updating the access token.
  94. */
  95. DriveClient.prototype.tokenRefreshInterval = 0;
  96. /**
  97. * Interval for updating the access token.
  98. */
  99. DriveClient.prototype.lastTokenRefresh = 0;
  100. /**
  101. * Executes the first step for connecting to Google Drive.
  102. */
  103. DriveClient.prototype.maxRetries = 4;
  104. /**
  105. * Executes the first step for connecting to Google Drive.
  106. */
  107. DriveClient.prototype.mimeTypeCheckCoolOff = 60000;
  108. /**
  109. * Executes the first step for connecting to Google Drive.
  110. */
  111. DriveClient.prototype.user = null;
  112. /**
  113. * Authorizes the client, gets the userId and calls <open>.
  114. */
  115. DriveClient.prototype.setUser = function(user)
  116. {
  117. this.user = user;
  118. if (this.user == null && this.tokenRefreshThread != null)
  119. {
  120. window.clearTimeout(this.tokenRefreshThread);
  121. this.tokenRefreshThread = null;
  122. }
  123. this.fireEvent(new mxEventObject('userChanged'));
  124. };
  125. /**
  126. * Authorizes the client, gets the userId and calls <open>.
  127. */
  128. DriveClient.prototype.getUser = function()
  129. {
  130. return this.user;
  131. };
  132. /**
  133. * Authorizes the client, gets the userId and calls <open>.
  134. */
  135. DriveClient.prototype.setUserId = function(userId, remember)
  136. {
  137. if (remember)
  138. {
  139. if (isLocalStorage)
  140. {
  141. localStorage.setItem('.guid', userId);
  142. }
  143. else if (typeof(Storage) != 'undefined')
  144. {
  145. try
  146. {
  147. var expiry = new Date();
  148. expiry.setYear(expiry.getFullYear() + 1);
  149. document.cookie = 'GUID=' + userId + '; expires=' + expiry.toUTCString();
  150. }
  151. catch (e)
  152. {
  153. // any errors for storing the user ID can be safely ignored
  154. }
  155. }
  156. }
  157. };
  158. /**
  159. * Authorizes the client, gets the userId and calls <open>.
  160. */
  161. DriveClient.prototype.clearUserId = function()
  162. {
  163. if (isLocalStorage)
  164. {
  165. localStorage.removeItem('.guid');
  166. }
  167. else if (typeof(Storage) != 'undefined')
  168. {
  169. var expiry = new Date();
  170. expiry.setYear(expiry.getFullYear() - 1);
  171. document.cookie = 'GUID=; expires=' + expiry.toUTCString();
  172. }
  173. };
  174. /**
  175. * Authorizes the client, gets the userId and calls <open>.
  176. */
  177. DriveClient.prototype.getUserId = function()
  178. {
  179. var uid = null;
  180. if (this.user != null)
  181. {
  182. uid = this.user.id;
  183. }
  184. if (uid == null && isLocalStorage)
  185. {
  186. uid = localStorage.getItem('.guid');
  187. }
  188. if (uid == null && typeof(Storage) != 'undefined')
  189. {
  190. var cookies = document.cookie.split(";");
  191. for (var i = 0; i < cookies.length; i++)
  192. {
  193. // Removes spaces around cookie
  194. var cookie = mxUtils.trim(cookies[i]);
  195. if (cookie.substring(0, 5) == 'GUID=')
  196. {
  197. uid = cookie.substring(5);
  198. break;
  199. }
  200. }
  201. if (uid != null && isLocalStorage)
  202. {
  203. // Moves to local storage
  204. var expiry = new Date();
  205. expiry.setYear(expiry.getFullYear() - 1);
  206. document.cookie = 'GUID=; expires=' + expiry.toUTCString();
  207. localStorage.setItem('.guid', uid);
  208. }
  209. }
  210. return uid;
  211. };
  212. /**
  213. * Authorizes the client, gets the userId and calls <open>.
  214. */
  215. DriveClient.prototype.execute = function(fn)
  216. {
  217. // Handles error in immediate authorize call via callback that shows a
  218. // UI with a button that executes the second non-immediate authorize
  219. var fallback = mxUtils.bind(this, function(resp)
  220. {
  221. // Remember is an argument for the callback that executes
  222. // when the user clicks the authorize button in the UI and
  223. // success executes after successful authorization.
  224. this.ui.showAuthDialog(this, true, mxUtils.bind(this, function(remember, success)
  225. {
  226. this.authorize(false, function()
  227. {
  228. if (success != null)
  229. {
  230. success();
  231. }
  232. fn();
  233. }, mxUtils.bind(this, function(resp)
  234. {
  235. var msg = mxResources.get('cannotLogin');
  236. // Handles special domain policy errors
  237. if (resp != null && resp.error != null && resp.error.code == 403 &&
  238. resp.error.data != null && resp.error.data.length > 0 &&
  239. resp.error.data[0].reason == 'domainPolicy')
  240. {
  241. msg = resp.error.message;
  242. }
  243. this.ui.drive.clearUserId();
  244. this.ui.drive.setUser(null);
  245. gapi.auth.signOut();
  246. this.ui.showError(mxResources.get('error'), msg, mxResources.get('ok'));
  247. }), remember);
  248. }));
  249. });
  250. // First immediate authorize attempt
  251. this.authorize(true, fn, fallback);
  252. };
  253. /**
  254. * Translates this point by the given vector.
  255. *
  256. * @param {number} dx X-coordinate of the translation.
  257. * @param {number} dy Y-coordinate of the translation.
  258. */
  259. DriveClient.prototype.executeRequest = function(req, success, error)
  260. {
  261. var acceptResponse = true;
  262. var timeoutThread = null;
  263. var retryCount = 0;
  264. // Cancels any pending requests
  265. if (this.requestThread != null)
  266. {
  267. window.clearTimeout(this.requestThread);
  268. }
  269. var fn = mxUtils.bind(this, function()
  270. {
  271. this.requestThread = null;
  272. this.currentRequest = req;
  273. if (timeoutThread != null)
  274. {
  275. window.clearTimeout(timeoutThread);
  276. }
  277. timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  278. {
  279. acceptResponse = false;
  280. if (error != null)
  281. {
  282. error({code: App.ERROR_TIMEOUT, retry: fn});
  283. }
  284. }), this.ui.timeout);
  285. req.execute(mxUtils.bind(this, function(resp)
  286. {
  287. window.clearTimeout(timeoutThread);
  288. if (acceptResponse)
  289. {
  290. if (resp != null && resp.error == null)
  291. {
  292. if (success != null)
  293. {
  294. success(resp);
  295. }
  296. }
  297. else
  298. {
  299. // Handles special error for saving old file where mime was changed to new
  300. // LATER: Check if 403 is never auth error, for now we check the message for a specific
  301. // case where the old app mime type was overridden by the new app
  302. if (error != null && resp != null && resp.error != null && resp.error.code == 403 &&
  303. (resp.error.message == 'The requested mime type change is forbidden.' ||
  304. resp.error.data != null && resp.error.data[0].reason == 'domainPolicy'))
  305. {
  306. error(resp);
  307. }
  308. // Handles authentication error
  309. else if (resp != null && resp.error != null && (resp.error.code == 401 || resp.error.code == 403))
  310. {
  311. // Shows an error if we're authenticated but the server still doesn't allow it
  312. if (resp.error.code == 403 && this.user != null)
  313. {
  314. if (error != null)
  315. {
  316. error(resp);
  317. }
  318. }
  319. else
  320. {
  321. this.execute(fn);
  322. }
  323. }
  324. // Schedules a retry if no new request was executed
  325. // TODO: Check for 'rateLimitExceeded', 'userRateLimitExceeded' in errors
  326. // see https://developers.google.com/drive/handle-errors
  327. else if (resp != null && resp.error != null && resp.error.code != 404 && this.currentRequest == req && retryCount < this.maxRetries)
  328. {
  329. retryCount++;
  330. var jitter = 1 + 0.1 * (Math.random() - 0.5);
  331. this.requestThread = window.setTimeout(fn, Math.round(Math.pow(2, retryCount) * jitter * 1000));
  332. }
  333. else if (error != null)
  334. {
  335. error(resp);
  336. }
  337. }
  338. }
  339. }));
  340. });
  341. // Must get token before first request in this case
  342. if (gapi.auth.getToken() == null)
  343. {
  344. this.execute(fn);
  345. }
  346. else
  347. {
  348. fn();
  349. }
  350. },
  351. /**
  352. * Authorizes the client, gets the userId and calls <open>.
  353. */
  354. DriveClient.prototype.authorize = function(immediate, success, error, remember)
  355. {
  356. var userId = this.getUserId();
  357. // Takes userId from state URL parameter
  358. if (this.ui.stateArg != null && this.ui.stateArg.userId != null)
  359. {
  360. userId = this.ui.stateArg.userId;
  361. }
  362. // Immediate only possible with userId
  363. if (immediate && userId == null)
  364. {
  365. if (error != null)
  366. {
  367. error();
  368. }
  369. }
  370. else
  371. {
  372. var params =
  373. {
  374. scope: this.scopes,
  375. client_id: this.clientId
  376. };
  377. if (immediate && userId != null)
  378. {
  379. params.immediate = true;
  380. params.user_id = userId;
  381. }
  382. else
  383. {
  384. params.immediate = false;
  385. params.authuser = -1;
  386. }
  387. gapi.auth.authorize(params, mxUtils.bind(this, function(resp)
  388. {
  389. // Updates the current user info
  390. if (resp != null && resp.error == null)
  391. {
  392. if (this.user == null || !immediate || this.user.id != userId)
  393. {
  394. this.updateUser(success, error, remember);
  395. }
  396. else if (success != null)
  397. {
  398. success();
  399. }
  400. }
  401. else if (error != null)
  402. {
  403. error(resp);
  404. }
  405. this.resetTokenRefresh(resp);
  406. }));
  407. }
  408. };
  409. /**
  410. * Checks if the client is authorized and calls the next step.
  411. */
  412. DriveClient.prototype.resetTokenRefresh = function(resp)
  413. {
  414. if (this.tokenRefreshThread != null)
  415. {
  416. window.clearTimeout(this.tokenRefreshThread);
  417. this.tokenRefreshThread = null;
  418. }
  419. // Starts timer to refresh token before it expires
  420. if (resp != null && resp.error == null && resp.expires_in > 0)
  421. {
  422. this.tokenRefreshInterval = parseInt(resp.expires_in) * 1000;
  423. this.lastTokenRefresh = new Date().getTime();
  424. this.tokenRefreshThread = window.setTimeout(mxUtils.bind(this, function()
  425. {
  426. this.authorize(true, mxUtils.bind(this, function()
  427. {
  428. //console.log('tokenRefresh: refreshed', gapi.auth.getToken());
  429. }), mxUtils.bind(this, function()
  430. {
  431. //console.log('tokenRefresh: error refreshing', gapi.auth.getToken());
  432. }));
  433. }), resp.expires_in * 900);
  434. }
  435. };
  436. /**
  437. * Checks if the client is authorized and calls the next step.
  438. */
  439. DriveClient.prototype.checkToken = function(fn)
  440. {
  441. var connected = this.lastTokenRefresh > 0;
  442. var delta = new Date().getTime() - this.lastTokenRefresh;
  443. if (delta > this.tokenRefreshInterval || this.tokenRefreshThread == null)
  444. {
  445. // Uses execute instead of authorize to allow a fallback authorization if cookie was lost
  446. this.execute(mxUtils.bind(this, function()
  447. {
  448. fn();
  449. if (connected)
  450. {
  451. this.fireEvent(new mxEventObject('disconnected'));
  452. }
  453. }));
  454. }
  455. else
  456. {
  457. fn();
  458. }
  459. };
  460. /**
  461. * Checks if the client is authorized and calls the next step.
  462. */
  463. DriveClient.prototype.updateUser = function(success, error, remember)
  464. {
  465. var token = gapi.auth.getToken().access_token;
  466. var url = 'https://www.googleapis.com/oauth2/v2/userinfo?alt=json&access_token=' + token;
  467. this.ui.loadUrl(url, mxUtils.bind(this, function(data)
  468. {
  469. var info = JSON.parse(data);
  470. // Requests more information about the user
  471. this.executeRequest(gapi.client.drive.about.get(), mxUtils.bind(this, function(resp)
  472. {
  473. this.setUser(new DrawioUser(info.id, resp.user.emailAddress, resp.user.displayName,
  474. (resp.user.picture != null) ? resp.user.picture.url : null, info.locale));
  475. this.setUserId(info.id, remember);
  476. if (success != null)
  477. {
  478. success();
  479. }
  480. }), error);
  481. }), error);
  482. };
  483. /**
  484. * Translates this point by the given vector.
  485. *
  486. * @param {number} dx X-coordinate of the translation.
  487. * @param {number} dy Y-coordinate of the translation.
  488. */
  489. DriveClient.prototype.copyFile = function(id, title, success, error)
  490. {
  491. if (id != null && title != null)
  492. {
  493. this.executeRequest(gapi.client.drive.files.copy({'fileId': id, 'resource':
  494. {'title' : title}, 'supportsTeamDrives': true}), success, error);
  495. }
  496. };
  497. /**
  498. * Translates this point by the given vector.
  499. *
  500. * @param {number} dx X-coordinate of the translation.
  501. * @param {number} dy Y-coordinate of the translation.
  502. */
  503. DriveClient.prototype.renameFile = function(id, title, success, error)
  504. {
  505. if (id != null && title != null)
  506. {
  507. this.executeRequest(this.createDriveRequest(id, {'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.moveFile = function(id, folderId, success, error)
  517. {
  518. if (id != null && folderId != null)
  519. {
  520. this.executeRequest(this.createDriveRequest(id, {'parents': [{'kind':
  521. 'drive#fileLink', 'id': folderId}]}), 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.createDriveRequest = function(id, body)
  531. {
  532. return gapi.client.request({
  533. 'path': '/drive/v2/files/' + id,
  534. 'method': 'PUT',
  535. 'params': {'uploadType' : 'multipart', 'supportsTeamDrives': true},
  536. 'headers': {'Content-Type': 'application/json; charset=UTF-8'},
  537. 'body': JSON.stringify(body)
  538. });
  539. };
  540. /**
  541. * Loads the given file as a library file.
  542. */
  543. DriveClient.prototype.getLibrary = function(id, success, error)
  544. {
  545. return this.getFile(id, success, error, true, true);
  546. };
  547. /**
  548. * Checks if the client is authorized and calls the next step. The optional
  549. * readXml argument is used for import. Default is false. The optional
  550. * readLibrary argument is used for reading libraries. Default is false.
  551. */
  552. DriveClient.prototype.getFile = function(id, success, error, readXml, readLibrary)
  553. {
  554. readXml = (readXml != null) ? readXml : false;
  555. readLibrary = (readLibrary != null) ? readLibrary : false;
  556. if (urlParams['rev'] != null)
  557. {
  558. this.executeRequest(gapi.client.drive.revisions.get({'fileId': id, 'revisionId': urlParams['rev']}), mxUtils.bind(this, function(resp)
  559. {
  560. this.getXmlFile(resp, null, success, error);
  561. }), error);
  562. }
  563. else
  564. {
  565. this.executeRequest(gapi.client.drive.files.get({'fileId': id, 'supportsTeamDrives': true}), mxUtils.bind(this, function(resp)
  566. {
  567. if (this.user != null)
  568. {
  569. // Handles .vsdx, Gliffy and PNG+XML files by creating a temporary file
  570. if ((/\.vsdx$/i.test(resp.title) || /\.gliffy$/i.test(resp.title) || /\.png$/i.test(resp.title)))
  571. {
  572. var url = resp.downloadUrl + '&access_token=' + gapi.auth.getToken().access_token;
  573. this.ui.convertFile(url, resp.title, resp.mimeType, this.extension, success, error);
  574. }
  575. else
  576. {
  577. if (readXml || readLibrary || resp.mimeType == this.libraryMimeType)
  578. {
  579. this.getXmlFile(resp, null, success, error, true, readLibrary);
  580. }
  581. else
  582. {
  583. this.loadRealtime(resp, mxUtils.bind(this, function(doc)
  584. {
  585. try
  586. {
  587. // Converts XML files to realtime including old realtime model
  588. if (doc == null || doc.getModel() == null || doc.getModel().getRoot() == null ||
  589. doc.getModel().getRoot().isEmpty() || (doc.getModel().getRoot().has('cells') &&
  590. !doc.getModel().getRoot().has(DriveRealtime.prototype.diagramsKey)))
  591. {
  592. this.getXmlFile(resp, doc, success, error);
  593. }
  594. else
  595. {
  596. // XML not required here since the realtime model is not empty
  597. success(new DriveFile(this.ui, null, resp, doc));
  598. }
  599. }
  600. catch (e)
  601. {
  602. error(e);
  603. }
  604. }), error);
  605. }
  606. }
  607. }
  608. else
  609. {
  610. error({message: mxResources.get('loggedOut')});
  611. }
  612. }), error);
  613. }
  614. };
  615. /**
  616. * Checks if the client is authorized and calls the next step.
  617. */
  618. DriveClient.prototype.loadRealtime = function(resp, success, error)
  619. {
  620. // Redirects to new app because the realtime models of different apps are not visible
  621. if (urlParams['ignoremime'] != '1' && this.appId == '420247213240' &&
  622. (resp.mimeType == 'application/vnd.jgraph.mxfile.realtime' ||
  623. resp.mimeType == 'application/mxr'))
  624. {
  625. this.redirectToNewApp(error, resp.id);
  626. }
  627. // Checks if we're in viewer app or if the file is writeable if it needs to be converted
  628. else if (this.appId != '850530949725' && (resp.editable || (resp.mimeType != 'application/mxe' &&
  629. resp.mimeType != 'application/vnd.jgraph.mxfile')))
  630. {
  631. var fn = mxUtils.bind(this, function()
  632. {
  633. var acceptResponse = true;
  634. var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  635. {
  636. acceptResponse = false;
  637. error({code: App.ERROR_TIMEOUT, retry: fn});
  638. }), this.ui.timeout);
  639. gapi.drive.realtime.load(resp.id, mxUtils.bind(this, function(doc)
  640. {
  641. window.clearTimeout(timeoutThread);
  642. if (acceptResponse)
  643. {
  644. success(doc);
  645. }
  646. }));
  647. });
  648. fn();
  649. }
  650. // Shows the file as read-only without conversion
  651. else
  652. {
  653. success();
  654. }
  655. };
  656. /**
  657. * Checks if the client is authorized and calls the next step. The ignoreMime argument is
  658. * used for import via getFile. Default is false. The optional
  659. * readLibrary argument is used for reading libraries. Default is false.
  660. */
  661. DriveClient.prototype.getXmlFile = function(resp, doc, success, error, ignoreMime, readLibrary)
  662. {
  663. var token = gapi.auth.getToken().access_token;
  664. var url = resp.downloadUrl + '&access_token=' + token;
  665. // Loads XML to initialize realtime document if realtime is empty
  666. this.ui.loadUrl(url, mxUtils.bind(this, function(data)
  667. {
  668. if (data == null)
  669. {
  670. // TODO: Optional redirect to legacy if link is for old file
  671. error({message: mxResources.get('invalidOrMissingFile')});
  672. }
  673. else if (resp.mimeType == this.libraryMimeType || readLibrary)
  674. {
  675. if (resp.mimeType == this.libraryMimeType && !readLibrary)
  676. {
  677. error({message: mxResources.get('notADiagramFile')});
  678. }
  679. else
  680. {
  681. success(new DriveLibrary(this.ui, data, resp));
  682. }
  683. }
  684. else
  685. {
  686. var file = new DriveFile(this.ui, data, resp, doc);
  687. // Checks if mime-type needs to be updated if the file is editable and no viewer app
  688. if (!ignoreMime && this.appId != '850530949725' && file.isEditable() && resp.mimeType != this.mimeType)
  689. {
  690. // Overwrites mime-type (only mutable on update when uploading new content)
  691. this.saveFile(file, true, mxUtils.bind(this, function(resp)
  692. {
  693. file.desc = resp;
  694. success(file);
  695. }), error, true);
  696. }
  697. else
  698. {
  699. success(file);
  700. }
  701. }
  702. }), error, (resp.mimeType.substring(0, 6) == 'image/' && resp.mimeType.substring(0, 9) != 'image/svg') ||
  703. /\.png$/i.test(resp.title) || /\.jpe?g$/i.test(resp.title));
  704. };
  705. /**
  706. * Translates this point by the given vector.
  707. *
  708. * @param {number} dx X-coordinate of the translation.
  709. * @param {number} dy Y-coordinate of the translation.
  710. */
  711. DriveClient.prototype.saveFile = function(file, revision, success, error, noCheck, unloading)
  712. {
  713. if (file.isEditable())
  714. {
  715. var t0 = new Date().getTime();
  716. noCheck = (noCheck != null) ? noCheck : (!this.ui.isLegacyDriveDomain() || urlParams['ignoremime'] == '1');
  717. // NOTE: Unloading arg is currently ignored, saving during unload/beforeUnload is not possible using
  718. // asynchronous code, which is needed to create the thumbnail, or asynchronous requests which is the only
  719. // way to execute the gapi request below.
  720. // If no thumbnail is created and noCheck is true (which is always true if unloading is true) in which case
  721. // this code is synchronous, the executeRequest call is reached but the request is still not sent. This is
  722. // true for both, calls from beforeUnload and unload handlers. Note sure how to make the call synchronous
  723. // which is said to fix this when called from beforeUnload.
  724. // However, this would result in a missing thumbnail in most cases so a better solution might be to reduce
  725. // the autosave interval in DriveRealtime, but that would increase the number of requests.
  726. unloading = (unloading != null) ? unloading : false;
  727. // Adds optional thumbnail to upload request
  728. var doSave = mxUtils.bind(this, function(thumb, thumbMime, keepExisting)
  729. {
  730. var meta =
  731. {
  732. 'mimeType': (file.constructor == DriveLibrary) ? this.libraryMimeType : this.mimeType,
  733. 'title': file.getTitle()
  734. };
  735. // Specifies that no thumbnail should be uploaded in which case the existing thumbnail is used
  736. if (!keepExisting)
  737. {
  738. // Uses placeholder thumbnail to replace existing one except when unloading
  739. // in which case the XML is updated but the existing thumbnail is not in order
  740. // to avoid executing asynchronous code and get the XML to the server instead
  741. if (thumb == null && !unloading)
  742. {
  743. thumb = this.placeholderThumbnail;
  744. thumbMime = this.placeholderMimeType;
  745. }
  746. // Adds metadata for thumbnail
  747. if (thumb != null && thumbMime != null)
  748. {
  749. meta.thumbnail =
  750. {
  751. 'image': thumb,
  752. 'mimeType': thumbMime
  753. };
  754. }
  755. }
  756. // Updates saveDelay on drive file
  757. var wrapper = function()
  758. {
  759. file.saveDelay = new Date().getTime() - t0;
  760. success.apply(this, arguments);
  761. };
  762. this.executeRequest(this.createUploadRequest(file.getId(), meta,
  763. file.getData(), revision || (file.desc.mimeType != this.mimeType &&
  764. file.desc.mimeType != this.libraryMimeType)), wrapper, error);
  765. });
  766. // Indirection to generate thumbnails if enabled and supported
  767. // (required because generation of thumbnails is asynchronous)
  768. var fn = mxUtils.bind(this, function()
  769. {
  770. // NOTE: getThumbnail is asynchronous and returns false if no thumbnails can be created
  771. if (unloading || file.constructor == DriveLibrary || !this.enableThumbnails || urlParams['thumb'] == '0' ||
  772. !this.ui.getThumbnail(this.thumbnailWidth, mxUtils.bind(this, function(canvas)
  773. {
  774. // Callback for getThumbnail
  775. var thumb = null;
  776. if (canvas != null)
  777. {
  778. try
  779. {
  780. // Security errors are possible
  781. thumb = canvas.toDataURL('image/png');
  782. }
  783. catch (e)
  784. {
  785. // ignore and continue with placeholder
  786. }
  787. }
  788. // Maximum thumbnail size is 2MB
  789. if (thumb == null || thumb.length > this.maxThumbnailSize)
  790. {
  791. thumb = null;
  792. }
  793. else
  794. {
  795. // Converts base64 data into required format for Drive (base64url with no prefix)
  796. thumb = thumb.substring(thumb.indexOf(',') + 1).replace(/\+/g, '-').replace(/\//g, '_');
  797. }
  798. doSave(thumb, 'image/png');
  799. })))
  800. {
  801. // If-branch
  802. doSave(null, null, file.constructor != DriveLibrary);
  803. }
  804. });
  805. // New revision is required if mime type changes, but the mime type should not be replaced
  806. // if the file has been converted to the new realtime format. To check this we make sure
  807. // that the mime type has not changed before updating it in the case of the legacy app.
  808. // Note: We need to always check the mime type because saveFile cancels previous save
  809. // attempts so if the save frequency is higher than the time for all retries than you
  810. // will never see the error message and accumulate lots of changes that will be lost.
  811. if (noCheck || !revision)
  812. {
  813. fn();
  814. }
  815. else
  816. {
  817. this.verifyMimeType(file.getId(), fn, true);
  818. }
  819. }
  820. else
  821. {
  822. this.ui.editor.graph.reset();
  823. if (error != null)
  824. {
  825. error({message: mxResources.get('readOnly')});
  826. }
  827. }
  828. };
  829. /**
  830. * Verifies the mime type of the given file ID.
  831. */
  832. DriveClient.prototype.verifyMimeType = function(fileId, fn, force, error)
  833. {
  834. if (this.lastMimeCheck == null)
  835. {
  836. this.lastMimeCheck = 0;
  837. }
  838. var now = new Date().getTime();
  839. if (force || now - this.lastMimeCheck > this.mimeTypeCheckCoolOff)
  840. {
  841. this.lastMimeCheck = now;
  842. if (!this.checkingMimeType)
  843. {
  844. this.checkingMimeType = true;
  845. this.executeRequest(gapi.client.drive.files.get({'fileId': fileId, 'fields': 'mimeType', 'supportsTeamDrives': true}), mxUtils.bind(this, function(resp)
  846. {
  847. this.checkingMimeType = false;
  848. if (resp != null && resp.mimeType == 'application/vnd.jgraph.mxfile.realtime')
  849. {
  850. this.redirectToNewApp(error, fileId);
  851. }
  852. else if (fn != null)
  853. {
  854. fn();
  855. }
  856. }));
  857. }
  858. }
  859. };
  860. /**
  861. * Checks if the client is authorized and calls the next step.
  862. */
  863. DriveClient.prototype.redirectToNewApp = function(error, fileId)
  864. {
  865. this.ui.spinner.stop();
  866. if (!this.redirectDialogShowing)
  867. {
  868. this.redirectDialogShowing = true;
  869. var url = window.location.protocol + '//' + this.newAppHostname + '/' + this.ui.getSearch(
  870. ['create', 'title', 'mode', 'url', 'drive', 'splash']) + '#G' + fileId;
  871. if (error != null)
  872. {
  873. this.ui.confirm(mxResources.get('redirectToNewApp'), mxUtils.bind(this, function()
  874. {
  875. this.redirectDialogShowing = false;
  876. window.location.href = url;
  877. }), mxUtils.bind(this, function()
  878. {
  879. this.redirectDialogShowing = false;
  880. if (error != null)
  881. {
  882. error();
  883. }
  884. }));
  885. }
  886. else
  887. {
  888. this.ui.alert(mxResources.get('redirectToNewApp'), mxUtils.bind(this, function()
  889. {
  890. this.redirectDialogShowing = false;
  891. window.location.href = url;
  892. }));
  893. }
  894. }
  895. };
  896. /**
  897. * Translates this point by the given vector.
  898. *
  899. * @param {number} dx X-coordinate of the translation.
  900. * @param {number} dy Y-coordinate of the translation.
  901. */
  902. DriveClient.prototype.insertFile = function(title, data, folderId, success, error, mimeType, binary, allowRealtime)
  903. {
  904. mimeType = (mimeType != null) ? mimeType : this.mimeType;
  905. allowRealtime = (allowRealtime != null) ? allowRealtime : true;
  906. var metadata =
  907. {
  908. 'mimeType': mimeType,
  909. 'title': title
  910. };
  911. if (folderId != null)
  912. {
  913. metadata.parents = [{'kind': 'drive#fileLink', 'id': folderId}];
  914. }
  915. // NOTE: Cannot create thumbnail on insert since no ui has no current file
  916. this.executeRequest(this.createUploadRequest(null, metadata, data, false, binary), mxUtils.bind(this, function(resp)
  917. {
  918. if (mimeType == this.libraryMimeType)
  919. {
  920. success(new DriveLibrary(this.ui, data, resp));
  921. }
  922. else if (resp == false)
  923. {
  924. if (error != null)
  925. {
  926. error({message: mxResources.get('errorSavingFile')});
  927. }
  928. }
  929. else if (allowRealtime)
  930. {
  931. this.loadRealtime(resp, mxUtils.bind(this, function(doc)
  932. {
  933. if (this.user != null)
  934. {
  935. var file = new DriveFile(this.ui, data, resp, doc);
  936. // Avoids creating a new revision on first autosave of new files
  937. file.lastAutosaveRevision = new Date().getTime();
  938. success(file);
  939. }
  940. else if (error != null)
  941. {
  942. error({message: mxResources.get('loggedOut')});
  943. }
  944. }), error);
  945. }
  946. else
  947. {
  948. success(resp);
  949. }
  950. }), error);
  951. };
  952. /**
  953. * Translates this point by the given vector.
  954. *
  955. * @param {number} dx X-coordinate of the translation.
  956. * @param {number} dy Y-coordinate of the translation.
  957. */
  958. DriveClient.prototype.createUploadRequest = function(id, metadata, data, revision, binary)
  959. {
  960. binary = (binary != null) ? binary : false;
  961. var bd = '-------314159265358979323846';
  962. var delim = '\r\n--' + bd + '\r\n';
  963. var close = '\r\n--' + bd + '--';
  964. var ctype = 'application/octect-stream';
  965. var reqObj =
  966. {
  967. 'path': '/upload/drive/v2/files' + (id != null ? '/' + id : ''),
  968. 'method': (id != null) ? 'PUT' : 'POST',
  969. 'params': {'uploadType': 'multipart'},
  970. 'headers': {'Content-Type' : 'multipart/mixed; boundary="' + bd + '"'},
  971. 'body' : delim + 'Content-Type: application/json\r\n\r\n' + JSON.stringify(metadata) + delim +
  972. 'Content-Type: ' + ctype + '\r\n' + 'Content-Transfer-Encoding: base64\r\n' + '\r\n' +
  973. ((data != null) ? (binary) ? data : Base64.encode(data) : '') + close
  974. }
  975. if (!revision)
  976. {
  977. reqObj.params['newRevision'] = false;
  978. }
  979. reqObj.params['supportsTeamDrives'] = true;
  980. return gapi.client.request(reqObj);
  981. };
  982. /**
  983. * Translates this point by the given vector.
  984. *
  985. * @param {number} dx X-coordinate of the translation.
  986. * @param {number} dy Y-coordinate of the translation.
  987. */
  988. DriveClient.prototype.pickFile = function(fn, acceptAllFiles)
  989. {
  990. this.filePickerCallback = (fn != null) ? fn : mxUtils.bind(this, function(id)
  991. {
  992. this.ui.loadFile('G' + id);
  993. });
  994. this.filePicked = mxUtils.bind(this, function(data)
  995. {
  996. if (data.action == google.picker.Action.PICKED)
  997. {
  998. this.filePickerCallback(data.docs[0].id);
  999. }
  1000. });
  1001. if (this.ui.spinner.spin(document.body, mxResources.get('authorizing')))
  1002. {
  1003. this.execute(mxUtils.bind(this, function()
  1004. {
  1005. this.ui.spinner.stop();
  1006. // Reuses picker as long as token doesn't change.
  1007. var token = gapi.auth.getToken().access_token;
  1008. var name = (acceptAllFiles) ? 'genericPicker' : 'filePicker';
  1009. // Click on background closes dialog as workaround for blocking dialog
  1010. // states such as 401 where the dialog cannot be closed and blocks UI
  1011. var exit = mxUtils.bind(this, function(evt)
  1012. {
  1013. // Workaround for click from appIcon on second call
  1014. if (mxEvent.getSource(evt).className == 'picker modal-dialog-bg picker-dialog-bg')
  1015. {
  1016. mxEvent.removeListener(document, 'click', exit);
  1017. this[name].setVisible(false);
  1018. }
  1019. });
  1020. if (this[name] == null || this[name + 'Token'] != token)
  1021. {
  1022. // FIXME: Dispose not working
  1023. // if (this[name] != null)
  1024. // {
  1025. // console.log(name, this[name]);
  1026. // this[name].dispose();
  1027. // }
  1028. this[name + 'Token'] = token;
  1029. // Pseudo-hierarchical directory view, see
  1030. // https://groups.google.com/forum/#!topic/google-picker-api/FSFcuJe7icQ
  1031. var view = new google.picker.DocsView(google.picker.ViewId.FOLDERS)
  1032. .setParent('root')
  1033. .setIncludeFolders(true);
  1034. var view2 = new google.picker.DocsView();
  1035. var view3 = new google.picker.DocsUploadView()
  1036. .setIncludeFolders(true);
  1037. if (!acceptAllFiles)
  1038. {
  1039. view.setMimeTypes(this.mimeTypes);
  1040. view2.setMimeTypes(this.mimeTypes);
  1041. }
  1042. else
  1043. {
  1044. // Workaround for no files shown
  1045. view.setMimeTypes(this.mimeTypes + ',image/png,image/jpg,image/svg+xml,' +
  1046. 'application/xml,text/plain,text/html');
  1047. }
  1048. this[name] = new google.picker.PickerBuilder()
  1049. .setOAuthToken(this[name + 'Token'])
  1050. .setLocale(mxLanguage)
  1051. .setAppId(this.appId)
  1052. .addView(view)
  1053. .addView(view2)
  1054. .addView(google.picker.ViewId.RECENTLY_PICKED)
  1055. .addView(view3)
  1056. .setCallback(mxUtils.bind(this, function(data)
  1057. {
  1058. if (data.action == google.picker.Action.PICKED ||
  1059. data.action == google.picker.Action.CANCEL)
  1060. {
  1061. mxEvent.removeListener(document, 'click', exit);
  1062. }
  1063. if (data.action == google.picker.Action.PICKED)
  1064. {
  1065. this.filePicked(data);
  1066. }
  1067. })).build();
  1068. }
  1069. mxEvent.addListener(document, 'click', exit);
  1070. this[name].setVisible(true);
  1071. this.ui.movePickersToTop();
  1072. }));
  1073. }
  1074. };
  1075. /**
  1076. * Translates this point by the given vector.
  1077. *
  1078. * @param {number} dx X-coordinate of the translation.
  1079. * @param {number} dy Y-coordinate of the translation.
  1080. */
  1081. DriveClient.prototype.pickFolder = function(fn)
  1082. {
  1083. // Picker is initialized once and points to this function
  1084. // which is overridden each time to the picker is shown
  1085. this.folderPickerCallback = fn;
  1086. if (this.ui.spinner.spin(document.body, mxResources.get('authorizing')))
  1087. {
  1088. var showPicker = mxUtils.bind(this, function()
  1089. {
  1090. this.execute(mxUtils.bind(this, function()
  1091. {
  1092. this.ui.spinner.stop();
  1093. // Reuses picker as long as token doesn't change.
  1094. var token = gapi.auth.getToken().access_token;
  1095. var name = 'folderPicker';
  1096. // Click on background closes dialog as workaround for blocking dialog
  1097. // states such as 401 where the dialog cannot be closed and blocks UI
  1098. var exit = mxUtils.bind(this, function(evt)
  1099. {
  1100. // Workaround for click from appIcon on second call
  1101. if (mxEvent.getSource(evt).className == 'picker modal-dialog-bg picker-dialog-bg')
  1102. {
  1103. mxEvent.removeListener(document, 'click', exit);
  1104. this[name].setVisible(false);
  1105. }
  1106. });
  1107. if (this[name] == null || this[name + 'Token'] != token)
  1108. {
  1109. // FIXME: Dispose not working
  1110. // if (this[name] != null)
  1111. // {
  1112. // console.log(name, this[name]);
  1113. // this[name].dispose();
  1114. // }
  1115. this[name + 'Token'] = token;
  1116. // Pseudo-hierarchical directory view, see
  1117. // https://groups.google.com/forum/#!topic/google-picker-api/FSFcuJe7icQ
  1118. var view = new google.picker.DocsView(google.picker.ViewId.FOLDERS)
  1119. .setParent('root')
  1120. .setIncludeFolders(true)
  1121. .setSelectFolderEnabled(true)
  1122. .setMimeTypes('application/vnd.google-apps.folder');
  1123. var view2 = new google.picker.DocsView()
  1124. .setIncludeFolders(true)
  1125. .setSelectFolderEnabled(true)
  1126. .setMimeTypes('application/vnd.google-apps.folder');
  1127. this[name] = new google.picker.PickerBuilder()
  1128. .setSelectableMimeTypes('application/vnd.google-apps.folder')
  1129. .setOAuthToken(this[name + 'Token'])
  1130. .setLocale(mxLanguage)
  1131. .setAppId(this.appId)
  1132. .addView(view)
  1133. .addView(view2)
  1134. .addView(google.picker.ViewId.RECENTLY_PICKED)
  1135. .setTitle(mxResources.get('pickFolder'))
  1136. .setCallback(mxUtils.bind(this, function(data)
  1137. {
  1138. if (data.action == google.picker.Action.PICKED ||
  1139. data.action == google.picker.Action.CANCEL)
  1140. {
  1141. mxEvent.removeListener(document, 'click', exit);
  1142. }
  1143. this.folderPickerCallback(data);
  1144. })).build();
  1145. }
  1146. mxEvent.addListener(document, 'click', exit);
  1147. this[name].setVisible(true);
  1148. this.ui.movePickersToTop();
  1149. }));
  1150. });
  1151. // Does not show picker if there are no folders in the root
  1152. this.executeRequest(gapi.client.drive.children.list({'folderId': 'root', 'maxResults': 1,
  1153. 'q': 'trashed=false and mimeType=\'application/vnd.google-apps.folder\''}),
  1154. mxUtils.bind(this, function(res)
  1155. {
  1156. if (res == null || res.items == null || res.items.length == 0)
  1157. {
  1158. // Simulates a pick event
  1159. this.ui.spinner.stop();
  1160. fn({'action': google.picker.Action.PICKED, 'docs': [{'type': 'folder', 'id': 'root'}]});
  1161. }
  1162. else
  1163. {
  1164. showPicker();
  1165. }
  1166. }), mxUtils.bind(this, function(err)
  1167. {
  1168. showPicker();
  1169. }));
  1170. }
  1171. };
  1172. /**
  1173. * Translates this point by the given vector.
  1174. *
  1175. * @param {number} dx X-coordinate of the translation.
  1176. * @param {number} dy Y-coordinate of the translation.
  1177. */
  1178. DriveClient.prototype.pickLibrary = function(fn)
  1179. {
  1180. this.filePickerCallback = fn;
  1181. this.filePicked = mxUtils.bind(this, function(data)
  1182. {
  1183. if (data.action == google.picker.Action.PICKED)
  1184. {
  1185. this.filePickerCallback(data.docs[0].id);
  1186. }
  1187. else if (data.action == google.picker.Action.CANCEL && this.ui.getCurrentFile() == null)
  1188. {
  1189. this.ui.showSplash();
  1190. }
  1191. });
  1192. if (this.ui.spinner.spin(document.body, mxResources.get('authorizing')))
  1193. {
  1194. this.execute(mxUtils.bind(this, function()
  1195. {
  1196. this.ui.spinner.stop();
  1197. // Click on background closes dialog as workaround for blocking dialog
  1198. // states such as 401 where the dialog cannot be closed and blocks UI
  1199. var exit = mxUtils.bind(this, function(evt)
  1200. {
  1201. // Workaround for click from appIcon on second call
  1202. if (mxEvent.getSource(evt).className == 'picker modal-dialog-bg picker-dialog-bg')
  1203. {
  1204. mxEvent.removeListener(document, 'click', exit);
  1205. this.libraryPicker.setVisible(false);
  1206. }
  1207. });
  1208. // Reuses picker as long as token doesn't change.
  1209. var token = gapi.auth.getToken().access_token;
  1210. if (this.libraryPicker == null || this.libraryPickerToken != token)
  1211. {
  1212. // FIXME: Dispose not working
  1213. // if (this[name] != null)
  1214. // {
  1215. // console.log(name, this[name]);
  1216. // this[name].dispose();
  1217. // }
  1218. this.libraryPickerToken = token;
  1219. // Pseudo-hierarchical directory view, see
  1220. // https://groups.google.com/forum/#!topic/google-picker-api/FSFcuJe7icQ
  1221. var view = new google.picker.DocsView(google.picker.ViewId.FOLDERS)
  1222. .setParent('root')
  1223. .setIncludeFolders(true)
  1224. .setMimeTypes(this.libraryMimeType + ',application/xml,text/plain,application/octet-stream');
  1225. var view2 = new google.picker.DocsView()
  1226. .setMimeTypes(this.libraryMimeType + ',application/xml,text/plain,application/octet-stream');
  1227. var view3 = new google.picker.DocsUploadView()
  1228. .setIncludeFolders(true);
  1229. this.libraryPicker = new google.picker.PickerBuilder()
  1230. .setOAuthToken(this.libraryPickerToken)
  1231. .setLocale(mxLanguage)
  1232. .setAppId(this.appId)
  1233. .addView(view)
  1234. .addView(view2)
  1235. .addView(google.picker.ViewId.RECENTLY_PICKED)
  1236. .addView(view3)
  1237. .setCallback(mxUtils.bind(this, function(data)
  1238. {
  1239. if (data.action == google.picker.Action.PICKED ||
  1240. data.action == google.picker.Action.CANCEL)
  1241. {
  1242. mxEvent.removeListener(document, 'click', exit);
  1243. }
  1244. if (data.action == google.picker.Action.PICKED)
  1245. {
  1246. this.filePicked(data);
  1247. }
  1248. })).build();
  1249. }
  1250. mxEvent.addListener(document, 'click', exit);
  1251. this.libraryPicker.setVisible(true);
  1252. this.ui.movePickersToTop();
  1253. }));
  1254. }
  1255. };
  1256. /**
  1257. * Translates this point by the given vector.
  1258. *
  1259. * @param {number} dx X-coordinate of the translation.
  1260. * @param {number} dy Y-coordinate of the translation.
  1261. */
  1262. DriveClient.prototype.showPermissions = function(id)
  1263. {
  1264. this.checkToken(mxUtils.bind(this, function()
  1265. {
  1266. var shareClient = new gapi.drive.share.ShareClient(this.appId);
  1267. shareClient.setOAuthToken(gapi.auth.getToken().access_token);
  1268. shareClient.setItemIds([id]);
  1269. shareClient.showSettingsDialog();
  1270. }));
  1271. };