DriveClient.js 42 KB

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