DriveClient.js 44 KB

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