DriveClient.js 44 KB

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