session.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. var util = require('./util');
  2. // 按照文件特征值,缓存 UploadId
  3. var cacheKey = 'cos_sdk_upload_cache';
  4. var expires = 30 * 24 * 3600;
  5. var cache;
  6. var timer;
  7. var getCache = function () {
  8. try {
  9. var val = JSON.parse(localStorage.getItem(cacheKey));
  10. } catch (e) {
  11. }
  12. if (!val) val = [];
  13. cache = val;
  14. };
  15. var setCache = function () {
  16. try {
  17. localStorage.setItem(cacheKey, JSON.stringify(cache))
  18. } catch (e) {
  19. }
  20. };
  21. var init = function () {
  22. if (cache) return;
  23. getCache.call(this);
  24. // 清理太老旧的数据
  25. var changed = false;
  26. var now = Math.round(Date.now() / 1000);
  27. for (var i = cache.length - 1; i >= 0; i--) {
  28. var mtime = cache[i][2];
  29. if (!mtime || mtime + expires < now) {
  30. cache.splice(i, 1);
  31. changed = true;
  32. }
  33. }
  34. changed && setCache();
  35. };
  36. // 把缓存存到本地
  37. var save = function () {
  38. if (timer) return;
  39. timer = setTimeout(function () {
  40. setCache();
  41. timer = null;
  42. }, 400);
  43. };
  44. var mod = {
  45. using: {},
  46. // 标记 UploadId 正在使用
  47. setUsing: function (uuid) {
  48. mod.using[uuid] = true;
  49. },
  50. // 标记 UploadId 已经没在使用
  51. removeUsing: function (uuid) {
  52. delete mod.using[uuid];
  53. },
  54. // 用上传参数生成哈希值
  55. getFileId: function (file, ChunkSize, Bucket, Key) {
  56. if (file.name && file.size && file.lastModifiedDate && ChunkSize) {
  57. return util.md5([file.name, file.size, file.lastModifiedDate, ChunkSize, Bucket, Key].join('::'));
  58. } else {
  59. return null;
  60. }
  61. },
  62. // 获取文件对应的 UploadId 列表
  63. getUploadIdList: function (uuid) {
  64. if (!uuid) return null;
  65. init.call(this);
  66. var list = [];
  67. for (var i = 0; i < cache.length; i++) {
  68. if (cache[i][0] === uuid)
  69. list.push(cache[i][1]);
  70. }
  71. return list.length ? list : null;
  72. },
  73. // 缓存 UploadId
  74. saveUploadId: function (uuid, UploadId, limit) {
  75. init.call(this);
  76. if (!uuid) return;
  77. // 清理没用的 UploadId,js 文件没有 FilePath ,只清理相同记录
  78. for (var i = cache.length - 1; i >= 0; i--) {
  79. var item = cache[i];
  80. if (item[0] === uuid && item[1] === UploadId) {
  81. cache.splice(i, 1);
  82. }
  83. }
  84. cache.unshift([uuid, UploadId, Math.round(Date.now() / 1000)]);
  85. if (cache.length > limit) cache.splice(limit);
  86. save();
  87. },
  88. // UploadId 已用完,移除掉
  89. removeUploadId: function (UploadId) {
  90. init.call(this);
  91. delete mod.using[UploadId];
  92. for (var i = cache.length - 1; i >= 0; i--) {
  93. if (cache[i][1] === UploadId) cache.splice(i, 1)
  94. }
  95. save();
  96. },
  97. };
  98. module.exports = mod;