DriveClient.js 43 KB

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