DriveClient.js 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429
  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));
  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. var keepExistingThumb = this.ui.currentPage != null && this.ui.currentPage != this.ui.pages[0];
  771. // NOTE: getThumbnail is asynchronous and returns false if no thumbnails can be created
  772. if (unloading || file.constructor == DriveLibrary || !this.enableThumbnails || urlParams['thumb'] == '0' ||
  773. keepExistingThumb || !this.ui.getThumbnail(this.thumbnailWidth, mxUtils.bind(this, function(canvas)
  774. {
  775. // Callback for getThumbnail
  776. var thumb = null;
  777. if (canvas != null)
  778. {
  779. try
  780. {
  781. // Security errors are possible
  782. thumb = canvas.toDataURL('image/png');
  783. }
  784. catch (e)
  785. {
  786. // ignore and continue with placeholder
  787. }
  788. }
  789. // Maximum thumbnail size is 2MB
  790. if (thumb == null || thumb.length > this.maxThumbnailSize)
  791. {
  792. thumb = null;
  793. }
  794. else
  795. {
  796. // Converts base64 data into required format for Drive (base64url with no prefix)
  797. thumb = thumb.substring(thumb.indexOf(',') + 1).replace(/\+/g, '-').replace(/\//g, '_');
  798. }
  799. doSave(thumb, 'image/png');
  800. })))
  801. {
  802. // If-branch
  803. doSave(null, null, file.constructor != DriveLibrary && keepExistingThumb);
  804. }
  805. });
  806. // New revision is required if mime type changes, but the mime type should not be replaced
  807. // if the file has been converted to the new realtime format. To check this we make sure
  808. // that the mime type has not changed before updating it in the case of the legacy app.
  809. // Note: We need to always check the mime type because saveFile cancels previous save
  810. // attempts so if the save frequency is higher than the time for all retries than you
  811. // will never see the error message and accumulate lots of changes that will be lost.
  812. if (noCheck || !revision)
  813. {
  814. fn();
  815. }
  816. else
  817. {
  818. this.verifyMimeType(file.getId(), fn, true);
  819. }
  820. }
  821. else
  822. {
  823. this.ui.editor.graph.reset();
  824. if (error != null)
  825. {
  826. error({message: mxResources.get('readOnly')});
  827. }
  828. }
  829. };
  830. /**
  831. * Verifies the mime type of the given file ID.
  832. */
  833. DriveClient.prototype.verifyMimeType = function(fileId, fn, force, error)
  834. {
  835. if (this.lastMimeCheck == null)
  836. {
  837. this.lastMimeCheck = 0;
  838. }
  839. var now = new Date().getTime();
  840. if (force || now - this.lastMimeCheck > this.mimeTypeCheckCoolOff)
  841. {
  842. this.lastMimeCheck = now;
  843. if (!this.checkingMimeType)
  844. {
  845. this.checkingMimeType = true;
  846. this.executeRequest(gapi.client.drive.files.get({'fileId': fileId, 'fields': 'mimeType', 'supportsTeamDrives': true}), mxUtils.bind(this, function(resp)
  847. {
  848. this.checkingMimeType = false;
  849. if (resp != null && resp.mimeType == 'application/vnd.jgraph.mxfile.realtime')
  850. {
  851. this.redirectToNewApp(error, fileId);
  852. }
  853. else if (fn != null)
  854. {
  855. fn();
  856. }
  857. }));
  858. }
  859. }
  860. };
  861. /**
  862. * Checks if the client is authorized and calls the next step.
  863. */
  864. DriveClient.prototype.redirectToNewApp = function(error, fileId)
  865. {
  866. this.ui.spinner.stop();
  867. if (!this.redirectDialogShowing)
  868. {
  869. this.redirectDialogShowing = true;
  870. var url = window.location.protocol + '//' + this.newAppHostname + '/' + this.ui.getSearch(
  871. ['create', 'title', 'mode', 'url', 'drive', 'splash']) + '#G' + fileId;
  872. if (error != null)
  873. {
  874. this.ui.confirm(mxResources.get('redirectToNewApp'), mxUtils.bind(this, function()
  875. {
  876. this.redirectDialogShowing = false;
  877. window.location.href = url;
  878. }), mxUtils.bind(this, function()
  879. {
  880. this.redirectDialogShowing = false;
  881. if (error != null)
  882. {
  883. error();
  884. }
  885. }));
  886. }
  887. else
  888. {
  889. this.ui.alert(mxResources.get('redirectToNewApp'), mxUtils.bind(this, function()
  890. {
  891. this.redirectDialogShowing = false;
  892. window.location.href = url;
  893. }));
  894. }
  895. }
  896. };
  897. /**
  898. * Translates this point by the given vector.
  899. *
  900. * @param {number} dx X-coordinate of the translation.
  901. * @param {number} dy Y-coordinate of the translation.
  902. */
  903. DriveClient.prototype.insertFile = function(title, data, folderId, success, error, mimeType, binary, allowRealtime)
  904. {
  905. mimeType = (mimeType != null) ? mimeType : this.mimeType;
  906. allowRealtime = (allowRealtime != null) ? allowRealtime : true;
  907. var metadata =
  908. {
  909. 'mimeType': mimeType,
  910. 'title': title
  911. };
  912. if (folderId != null)
  913. {
  914. metadata.parents = [{'kind': 'drive#fileLink', 'id': folderId}];
  915. }
  916. // NOTE: Cannot create thumbnail on insert since no ui has no current file
  917. this.executeRequest(this.createUploadRequest(null, metadata, data, false, binary), mxUtils.bind(this, function(resp)
  918. {
  919. if (mimeType == this.libraryMimeType)
  920. {
  921. success(new DriveLibrary(this.ui, data, resp));
  922. }
  923. else if (resp == false)
  924. {
  925. if (error != null)
  926. {
  927. error({message: mxResources.get('errorSavingFile')});
  928. }
  929. }
  930. else if (allowRealtime)
  931. {
  932. this.loadRealtime(resp, mxUtils.bind(this, function(doc)
  933. {
  934. if (this.user != null)
  935. {
  936. var file = new DriveFile(this.ui, data, resp, doc);
  937. // Avoids creating a new revision on first autosave of new files
  938. file.lastAutosaveRevision = new Date().getTime();
  939. success(file);
  940. }
  941. else if (error != null)
  942. {
  943. error({message: mxResources.get('loggedOut')});
  944. }
  945. }), error);
  946. }
  947. else
  948. {
  949. success(resp);
  950. }
  951. }), error);
  952. };
  953. /**
  954. * Translates this point by the given vector.
  955. *
  956. * @param {number} dx X-coordinate of the translation.
  957. * @param {number} dy Y-coordinate of the translation.
  958. */
  959. DriveClient.prototype.createUploadRequest = function(id, metadata, data, revision, binary)
  960. {
  961. binary = (binary != null) ? binary : false;
  962. var bd = '-------314159265358979323846';
  963. var delim = '\r\n--' + bd + '\r\n';
  964. var close = '\r\n--' + bd + '--';
  965. var ctype = 'application/octect-stream';
  966. var reqObj =
  967. {
  968. 'path': '/upload/drive/v2/files' + (id != null ? '/' + id : ''),
  969. 'method': (id != null) ? 'PUT' : 'POST',
  970. 'params': {'uploadType': 'multipart'},
  971. 'headers': {'Content-Type' : 'multipart/mixed; boundary="' + bd + '"'},
  972. 'body' : delim + 'Content-Type: application/json\r\n\r\n' + JSON.stringify(metadata) + delim +
  973. 'Content-Type: ' + ctype + '\r\n' + 'Content-Transfer-Encoding: base64\r\n' + '\r\n' +
  974. ((data != null) ? (binary) ? data : Base64.encode(data) : '') + close
  975. }
  976. if (!revision)
  977. {
  978. reqObj.params['newRevision'] = false;
  979. }
  980. reqObj.params['supportsTeamDrives'] = true;
  981. return gapi.client.request(reqObj);
  982. };
  983. /**
  984. * Translates this point by the given vector.
  985. *
  986. * @param {number} dx X-coordinate of the translation.
  987. * @param {number} dy Y-coordinate of the translation.
  988. */
  989. DriveClient.prototype.pickFile = function(fn, acceptAllFiles)
  990. {
  991. this.filePickerCallback = (fn != null) ? fn : mxUtils.bind(this, function(id)
  992. {
  993. this.ui.loadFile('G' + id);
  994. });
  995. this.filePicked = mxUtils.bind(this, function(data)
  996. {
  997. if (data.action == google.picker.Action.PICKED)
  998. {
  999. this.filePickerCallback(data.docs[0].id);
  1000. }
  1001. });
  1002. if (this.ui.spinner.spin(document.body, mxResources.get('authorizing')))
  1003. {
  1004. this.execute(mxUtils.bind(this, function()
  1005. {
  1006. this.ui.spinner.stop();
  1007. // Reuses picker as long as token doesn't change.
  1008. var token = gapi.auth.getToken().access_token;
  1009. var name = (acceptAllFiles) ? 'genericPicker' : 'filePicker';
  1010. // Click on background closes dialog as workaround for blocking dialog
  1011. // states such as 401 where the dialog cannot be closed and blocks UI
  1012. var exit = mxUtils.bind(this, function(evt)
  1013. {
  1014. // Workaround for click from appIcon on second call
  1015. if (mxEvent.getSource(evt).className == 'picker modal-dialog-bg picker-dialog-bg')
  1016. {
  1017. mxEvent.removeListener(document, 'click', exit);
  1018. this[name].setVisible(false);
  1019. }
  1020. });
  1021. if (this[name] == null || this[name + 'Token'] != token)
  1022. {
  1023. // FIXME: Dispose not working
  1024. // if (this[name] != null)
  1025. // {
  1026. // console.log(name, this[name]);
  1027. // this[name].dispose();
  1028. // }
  1029. this[name + 'Token'] = token;
  1030. // Pseudo-hierarchical directory view, see
  1031. // https://groups.google.com/forum/#!topic/google-picker-api/FSFcuJe7icQ
  1032. var view = new google.picker.DocsView(google.picker.ViewId.FOLDERS)
  1033. .setParent('root')
  1034. .setIncludeFolders(true);
  1035. var view2 = new google.picker.DocsView();
  1036. var view3 = new google.picker.DocsUploadView()
  1037. .setIncludeFolders(true);
  1038. if (!acceptAllFiles)
  1039. {
  1040. view.setMimeTypes(this.mimeTypes);
  1041. view2.setMimeTypes(this.mimeTypes);
  1042. }
  1043. else
  1044. {
  1045. // Workaround for no files shown
  1046. view.setMimeTypes(this.mimeTypes + ',image/png,image/jpg,image/svg+xml,' +
  1047. 'application/xml,text/plain,text/html');
  1048. }
  1049. this[name] = new google.picker.PickerBuilder()
  1050. .setOAuthToken(this[name + 'Token'])
  1051. .setLocale(mxLanguage)
  1052. .setAppId(this.appId)
  1053. .addView(view)
  1054. .addView(view2)
  1055. .addView(google.picker.ViewId.RECENTLY_PICKED)
  1056. .addView(view3)
  1057. .setCallback(mxUtils.bind(this, function(data)
  1058. {
  1059. if (data.action == google.picker.Action.PICKED ||
  1060. data.action == google.picker.Action.CANCEL)
  1061. {
  1062. mxEvent.removeListener(document, 'click', exit);
  1063. }
  1064. if (data.action == google.picker.Action.PICKED)
  1065. {
  1066. this.filePicked(data);
  1067. }
  1068. })).build();
  1069. }
  1070. mxEvent.addListener(document, 'click', exit);
  1071. this[name].setVisible(true);
  1072. this.ui.movePickersToTop();
  1073. }));
  1074. }
  1075. };
  1076. /**
  1077. * Translates this point by the given vector.
  1078. *
  1079. * @param {number} dx X-coordinate of the translation.
  1080. * @param {number} dy Y-coordinate of the translation.
  1081. */
  1082. DriveClient.prototype.pickFolder = function(fn)
  1083. {
  1084. // Picker is initialized once and points to this function
  1085. // which is overridden each time to the picker is shown
  1086. this.folderPickerCallback = fn;
  1087. if (this.ui.spinner.spin(document.body, mxResources.get('authorizing')))
  1088. {
  1089. var showPicker = mxUtils.bind(this, function()
  1090. {
  1091. this.execute(mxUtils.bind(this, function()
  1092. {
  1093. this.ui.spinner.stop();
  1094. // Reuses picker as long as token doesn't change.
  1095. var token = gapi.auth.getToken().access_token;
  1096. var name = 'folderPicker';
  1097. // Click on background closes dialog as workaround for blocking dialog
  1098. // states such as 401 where the dialog cannot be closed and blocks UI
  1099. var exit = mxUtils.bind(this, function(evt)
  1100. {
  1101. // Workaround for click from appIcon on second call
  1102. if (mxEvent.getSource(evt).className == 'picker modal-dialog-bg picker-dialog-bg')
  1103. {
  1104. mxEvent.removeListener(document, 'click', exit);
  1105. this[name].setVisible(false);
  1106. }
  1107. });
  1108. if (this[name] == null || this[name + 'Token'] != token)
  1109. {
  1110. // FIXME: Dispose not working
  1111. // if (this[name] != null)
  1112. // {
  1113. // console.log(name, this[name]);
  1114. // this[name].dispose();
  1115. // }
  1116. this[name + 'Token'] = token;
  1117. // Pseudo-hierarchical directory view, see
  1118. // https://groups.google.com/forum/#!topic/google-picker-api/FSFcuJe7icQ
  1119. var view = new google.picker.DocsView(google.picker.ViewId.FOLDERS)
  1120. .setParent('root')
  1121. .setIncludeFolders(true)
  1122. .setSelectFolderEnabled(true)
  1123. .setMimeTypes('application/vnd.google-apps.folder');
  1124. var view2 = new google.picker.DocsView()
  1125. .setIncludeFolders(true)
  1126. .setSelectFolderEnabled(true)
  1127. .setMimeTypes('application/vnd.google-apps.folder');
  1128. this[name] = new google.picker.PickerBuilder()
  1129. .setSelectableMimeTypes('application/vnd.google-apps.folder')
  1130. .setOAuthToken(this[name + 'Token'])
  1131. .setLocale(mxLanguage)
  1132. .setAppId(this.appId)
  1133. .addView(view)
  1134. .addView(view2)
  1135. .addView(google.picker.ViewId.RECENTLY_PICKED)
  1136. .setTitle(mxResources.get('pickFolder'))
  1137. .setCallback(mxUtils.bind(this, function(data)
  1138. {
  1139. if (data.action == google.picker.Action.PICKED ||
  1140. data.action == google.picker.Action.CANCEL)
  1141. {
  1142. mxEvent.removeListener(document, 'click', exit);
  1143. }
  1144. this.folderPickerCallback(data);
  1145. })).build();
  1146. }
  1147. mxEvent.addListener(document, 'click', exit);
  1148. this[name].setVisible(true);
  1149. this.ui.movePickersToTop();
  1150. }));
  1151. });
  1152. // Does not show picker if there are no folders in the root
  1153. this.executeRequest(gapi.client.drive.children.list({'folderId': 'root', 'maxResults': 1,
  1154. 'q': 'trashed=false and mimeType=\'application/vnd.google-apps.folder\''}),
  1155. mxUtils.bind(this, function(res)
  1156. {
  1157. if (res == null || res.items == null || res.items.length == 0)
  1158. {
  1159. // Simulates a pick event
  1160. this.ui.spinner.stop();
  1161. fn({'action': google.picker.Action.PICKED, 'docs': [{'type': 'folder', 'id': 'root'}]});
  1162. }
  1163. else
  1164. {
  1165. showPicker();
  1166. }
  1167. }), mxUtils.bind(this, function(err)
  1168. {
  1169. showPicker();
  1170. }));
  1171. }
  1172. };
  1173. /**
  1174. * Translates this point by the given vector.
  1175. *
  1176. * @param {number} dx X-coordinate of the translation.
  1177. * @param {number} dy Y-coordinate of the translation.
  1178. */
  1179. DriveClient.prototype.pickLibrary = function(fn)
  1180. {
  1181. this.filePickerCallback = fn;
  1182. this.filePicked = mxUtils.bind(this, function(data)
  1183. {
  1184. if (data.action == google.picker.Action.PICKED)
  1185. {
  1186. this.filePickerCallback(data.docs[0].id);
  1187. }
  1188. else if (data.action == google.picker.Action.CANCEL && this.ui.getCurrentFile() == null)
  1189. {
  1190. this.ui.showSplash();
  1191. }
  1192. });
  1193. if (this.ui.spinner.spin(document.body, mxResources.get('authorizing')))
  1194. {
  1195. this.execute(mxUtils.bind(this, function()
  1196. {
  1197. this.ui.spinner.stop();
  1198. // Click on background closes dialog as workaround for blocking dialog
  1199. // states such as 401 where the dialog cannot be closed and blocks UI
  1200. var exit = mxUtils.bind(this, function(evt)
  1201. {
  1202. // Workaround for click from appIcon on second call
  1203. if (mxEvent.getSource(evt).className == 'picker modal-dialog-bg picker-dialog-bg')
  1204. {
  1205. mxEvent.removeListener(document, 'click', exit);
  1206. this.libraryPicker.setVisible(false);
  1207. }
  1208. });
  1209. // Reuses picker as long as token doesn't change.
  1210. var token = gapi.auth.getToken().access_token;
  1211. if (this.libraryPicker == null || this.libraryPickerToken != token)
  1212. {
  1213. // FIXME: Dispose not working
  1214. // if (this[name] != null)
  1215. // {
  1216. // console.log(name, this[name]);
  1217. // this[name].dispose();
  1218. // }
  1219. this.libraryPickerToken = token;
  1220. // Pseudo-hierarchical directory view, see
  1221. // https://groups.google.com/forum/#!topic/google-picker-api/FSFcuJe7icQ
  1222. var view = new google.picker.DocsView(google.picker.ViewId.FOLDERS)
  1223. .setParent('root')
  1224. .setIncludeFolders(true)
  1225. .setMimeTypes(this.libraryMimeType + ',application/xml,text/plain,application/octet-stream');
  1226. var view2 = new google.picker.DocsView()
  1227. .setMimeTypes(this.libraryMimeType + ',application/xml,text/plain,application/octet-stream');
  1228. var view3 = new google.picker.DocsUploadView()
  1229. .setIncludeFolders(true);
  1230. this.libraryPicker = new google.picker.PickerBuilder()
  1231. .setOAuthToken(this.libraryPickerToken)
  1232. .setLocale(mxLanguage)
  1233. .setAppId(this.appId)
  1234. .addView(view)
  1235. .addView(view2)
  1236. .addView(google.picker.ViewId.RECENTLY_PICKED)
  1237. .addView(view3)
  1238. .setCallback(mxUtils.bind(this, function(data)
  1239. {
  1240. if (data.action == google.picker.Action.PICKED ||
  1241. data.action == google.picker.Action.CANCEL)
  1242. {
  1243. mxEvent.removeListener(document, 'click', exit);
  1244. }
  1245. if (data.action == google.picker.Action.PICKED)
  1246. {
  1247. this.filePicked(data);
  1248. }
  1249. })).build();
  1250. }
  1251. mxEvent.addListener(document, 'click', exit);
  1252. this.libraryPicker.setVisible(true);
  1253. this.ui.movePickersToTop();
  1254. }));
  1255. }
  1256. };
  1257. /**
  1258. * Translates this point by the given vector.
  1259. *
  1260. * @param {number} dx X-coordinate of the translation.
  1261. * @param {number} dy Y-coordinate of the translation.
  1262. */
  1263. DriveClient.prototype.showPermissions = function(id)
  1264. {
  1265. this.checkToken(mxUtils.bind(this, function()
  1266. {
  1267. var shareClient = new gapi.drive.share.ShareClient(this.appId);
  1268. shareClient.setOAuthToken(gapi.auth.getToken().access_token);
  1269. shareClient.setItemIds([id]);
  1270. shareClient.showSettingsDialog();
  1271. }));
  1272. };