medias.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. class Media {
  2. #date = 0;
  3. md5sum = "";
  4. fixedSum = "";
  5. path = "";
  6. fileName = "";
  7. meta = {};
  8. fixedTags = [];
  9. version = 0;
  10. tags = [];
  11. writeAccess = false;
  12. thumbnail = "";
  13. original = "";
  14. ui = null;
  15. constructor(data) {
  16. this.#date = data.date;
  17. this.md5sum = data.md5sum;
  18. this.fixedSum = data.fixedSum;
  19. this.path = data.path;
  20. this.fileName = data.fileName;
  21. this.meta = data.meta || {};
  22. this.fixedTags = [];
  23. this.version = data.version;
  24. this.tags = [];
  25. this.writeAccess = data.writeAccess !== undefined ? data.writeAccess : (data.accessType === 2);
  26. this.thumbnail = `/api/media/thumbnail/${data.fixedSum}.jpg`;
  27. this.original = `/api/media/original/${data.fixedSum}`;
  28. this.ui = null;
  29. this.setTags(data.fixedTags || [], data.tags || []);
  30. for (let i in this.meta) {
  31. if (this.meta[i].type === 'date')
  32. this.meta[i].value = new Date(parseInt(this.meta[i].value));
  33. else if (this.meta[i].type === 'number' || this.meta[i].type === 'octet')
  34. this.meta[i].value = parseInt(this.meta[i].value);
  35. else if (this.meta[i].type === 'string')
  36. this.meta[i].value = '' + this.meta[i].value;
  37. }
  38. }
  39. getDateTs() {
  40. return this.#date;
  41. }
  42. getDate() {
  43. return new Date(this.#date);
  44. }
  45. resize(maxWidth, maxHeight) {
  46. let ratio = Math.min(1, Math.max(
  47. maxWidth / (this.meta?.width?.value || maxWidth),
  48. maxHeight / (this.meta?.height?.value || maxHeight)));
  49. let result = {
  50. width: Math.floor(this.meta.width?.value *ratio),
  51. height: Math.floor(this.meta.height?.value *ratio),
  52. };
  53. if (isNaN(result.width) || isNaN(result.height) || !result.height || !result.width) {
  54. console.error("Failed to resize image ", this);
  55. return null;
  56. }
  57. return result;
  58. }
  59. setTags(fixedTags, tags) {
  60. this.tags = tags.reduce((acc, tag) => { acc.add(tag.replaceAll(/\/\/+/gi, '/')); return acc; }, new Set());
  61. this.fixedTags = fixedTags.reduce((acc, tag) => { acc.add(tag.replaceAll(/\/\/+/gi, '/')); return acc; }, new Set());
  62. }
  63. allTags() {
  64. return Array.from(new Set([...this.fixedTags, ...this.tags])).sort();
  65. }
  66. }
  67. function tryLoadMedia(md5sum) {
  68. return new Promise((ok, ko) => {
  69. $.get("/api/media/" +md5sum, data => {
  70. let item = new Media(data);
  71. MediaStorage.Instance.pushAll([item], true);
  72. ok(item);
  73. }).fail(err => {
  74. console.error("Trying to get media with md5sum " +md5sum +" failed:", err.responseText);
  75. ok(null);
  76. });
  77. });
  78. }
  79. class MediaStorage extends EventTarget
  80. {
  81. allMeta = {};
  82. allMetaTypes = {};
  83. allTags = new Set();
  84. medias = [];
  85. oldest = null;
  86. newest = null;
  87. #dbVersion = 0;
  88. loadingVersion = 0;
  89. constructor() {
  90. super();
  91. this.#reset();
  92. }
  93. #reset() {
  94. this.allMeta = {};
  95. this.allMetaTypes = {};
  96. this.allTags = new Set();
  97. this.medias = [];
  98. this.oldest = null;
  99. this.newest = null;
  100. this.#dbVersion = 0;
  101. this.loadingVersion = 0;
  102. }
  103. async rebuildMetaList() {
  104. this.#reset();
  105. this.dispatchEvent(new CustomEvent("rebuildMedia"));
  106. window.chronology.reset();
  107. this.downloadMetaList();
  108. }
  109. update() {
  110. this.downloadMetaList(true);
  111. }
  112. async restoreMetaList() {
  113. if (this.isLoading())
  114. return;
  115. this.#reset();
  116. this.#isLoading = true;
  117. document.getElementById("pch-infiniteScrollLoading").classList.remove("hidden");
  118. let hasData = false;
  119. try {
  120. await LoadingTasks.push(async () => {
  121. let data = await window.indexedData.listMedias();
  122. this.pushAll(data.medias.map(x => new Media(x)));
  123. this.#updateDbVersion(data.version);
  124. this.#isLoading = false;
  125. hasData = !!(data.medias?.length);
  126. });
  127. } catch (err) {
  128. console.error(err);
  129. }
  130. this.downloadMetaList(hasData);
  131. }
  132. #doDownloadMetaList(isUpdate) {
  133. this.#isLoading = true;
  134. document.getElementById("pch-infiniteScrollLoading").classList.remove("hidden");
  135. LoadingTasks.push(() => {
  136. return new Promise(ok => {
  137. let chronology = window.chronology.isInitialized() ? "" : "&chronology"
  138. let oldest = isUpdate !== true ? (this.oldest?.getDateTs() || 0) : 0;
  139. let oldestArg = oldest ? `&from=${oldest}` : "";
  140. let requestCount = 300;
  141. $.get(`/api/media/list?count=${requestCount}${chronology}${oldestArg}&version=${this.#dbVersion}`, async data => {
  142. this.pushAll(data.data.map(i => new Media(i)));
  143. if (data.first || data.last)
  144. window.chronology.rebuildRange(data.first, data.last);
  145. if (data.maxVersion)
  146. this.loadingVersion = parseInt(data.maxVersion);
  147. if ((data.data?.length || 0) < requestCount) {
  148. this.#isLoading = false;
  149. this.#updateDbVersion(this.loadingVersion);
  150. window.ReloadFilters(MediaStorage.Instance);
  151. this.dispatchEvent(new CustomEvent("doneLoading"));
  152. document.getElementById("pch-infiniteScrollLoading").classList.add("hidden");
  153. } else {
  154. this.#doDownloadMetaList(false);
  155. }
  156. ok();
  157. });
  158. });
  159. });
  160. }
  161. downloadMetaList(isUpdate) {
  162. if (this.isLoading())
  163. return;
  164. this.#doDownloadMetaList(isUpdate);
  165. }
  166. getDbVersion() { return this.#dbVersion; }
  167. #updateDbVersion(version) {
  168. this.#dbVersion = Math.max(this.#dbVersion, version);
  169. }
  170. #pushMeta(metaKey, metaVal) {
  171. if (metaKey === 'dateTime')
  172. return;
  173. if (!this.allMeta[metaKey])
  174. this.allMeta[metaKey] = new Set();
  175. this.allMeta[metaKey].add(metaVal.value);
  176. if (!this.allMetaTypes[metaKey])
  177. this.allMetaTypes[metaKey] = { type: metaVal.type, canBeEmpty: !!this.medias.length, canWrite: metaVal.canWrite };
  178. }
  179. #pushTag(tag, first) {
  180. while (tag.length && tag.endsWith('/'))
  181. tag = tag.substr(0, tag.length -1);
  182. this.allTags.add(tag);
  183. let index = tag.lastIndexOf('/');
  184. if (index >= 0)
  185. this.#pushTag(tag.substr(0, index));
  186. }
  187. #pushUnique(media) {
  188. for (let i of media.tags)
  189. this.#pushTag(i, true);
  190. for (let i of media.fixedTags)
  191. this.#pushTag(i, true);
  192. for (let key in media.meta)
  193. this.#pushMeta(key, media.meta[key]);
  194. for (let key in this.allMetaTypes)
  195. if (!media.meta[key])
  196. this.allMetaTypes[key].canBeEmpty = true;
  197. this.medias.push(media);
  198. }
  199. #isLoading = false;
  200. isLoading() { return this.#isLoading; }
  201. pushAll(arr, partialLoad) {
  202. let reorder = false;
  203. let newItems = [];
  204. for (let i of arr) {
  205. this.loadingVersion = Math.max(this.loadingVersion, i.version);
  206. if (partialLoad !== true) {
  207. this.oldest = !this.oldest || this.oldest.getDateTs() > i.getDateTs() ? i : this.oldest;
  208. this.newest = !this.newest || this.newest.getDateTs() < i.getDateTs() ? i : this.newest;
  209. }
  210. if (this.medias.length && this.medias[this.medias.length -1].getDateTs() < i.getDateTs())
  211. reorder = true;
  212. let previous = this.medias.find(x => x.fixedSum === i.fixedSum);
  213. if (previous) {
  214. this.medias = this.medias.filter(x => x.fixedSum !== i.fixedSum);
  215. i.ui = previous.ui;
  216. } else {
  217. newItems.push(i);
  218. }
  219. this.#pushUnique(i);
  220. }
  221. for (let i of newItems)
  222. this.dispatchEvent(new CustomEvent("newMedia", { detail: i }));
  223. if (reorder) {
  224. this.medias.sort((a, b) => b.getDateTs() - a.getDateTs());
  225. this.dispatchEvent(new CustomEvent("rebuildMedia"));
  226. }
  227. }
  228. onFilterUpdated() {
  229. this.dispatchEvent(new CustomEvent("rebuildMedia"));
  230. }
  231. getMediaIndex(media) {
  232. return this.medias.indexOf(media);
  233. }
  234. nextMedia(current) {
  235. return this.medias[this.getMediaIndex(current) +1];
  236. }
  237. previousMedia(current) {
  238. return this.medias[this.getMediaIndex(current) -1];
  239. }
  240. getMediaBetweenIndexes(a, b) {
  241. if (a > b)
  242. return this.getMediaBetweenIndexes(b, a);
  243. return this.medias.slice(a, b +1);
  244. }
  245. getMediaBetween(a, b) {
  246. let aIndex = this.medias.indexOf(a);
  247. let bIndex = this.medias.indexOf(b);
  248. if (aIndex < 0 || bIndex < 0 || aIndex === bIndex)
  249. return [];
  250. return this.getMediaBetweenIndexes(aIndex, bIndex);
  251. }
  252. removeMedia(md5sums) {
  253. let medias = this.medias.filter(x => md5sums.indexOf(x.fixedSum) >= 0);
  254. this.medias = this.medias.filter(x => md5sums.indexOf(x.fixedSum) === -1);
  255. for (let i of medias) {
  256. i.ui && i.ui.root.remove();
  257. this.dispatchEvent(new CustomEvent("mediaRemoved", { detail: i }));
  258. }
  259. }
  260. getMediaLocal(md5sum) {
  261. if (!md5sum)
  262. return null;
  263. return this.medias.find(x => x.fixedSum === md5sum);
  264. }
  265. async remoteRemove(md5Sums) {
  266. for (let md5sum of md5Sums) {
  267. await new Promise(ok => {
  268. $.ajax({
  269. url: `/api/media/${encodeURIComponent(md5sum)}`,
  270. type: "DELETE",
  271. success: ok,
  272. error: err => { console.error(err); ok() },
  273. });
  274. });
  275. }
  276. await indexedData.removeItems(md5Sums);
  277. this.removeMedia(md5Sums);
  278. }
  279. async getMedia(md5sum) {
  280. if (!md5sum)
  281. return null;
  282. let media = this.medias.find(x => x.fixedSum === md5sum);
  283. if (media)
  284. return media;
  285. return await tryLoadMedia(md5sum);
  286. }
  287. setMetaValue(md5sum, key, value) {
  288. let md5arr = undefined;
  289. if (Array.isArray(md5sum) && md5sum.length === 1)
  290. md5sum = md5sum[0];
  291. if (Array.isArray(md5sum)) {
  292. md5arr = md5sum;
  293. md5sum = "list";
  294. }
  295. return LoadingTasks.push(() => {
  296. return new Promise(ok => {
  297. let mediaCount = (md5arr || [ md5sum ]).map(checksum => this.medias.find(x => x.fixedSum === checksum)).filter(x => x.writeAccess).length;
  298. if (mediaCount != (md5arr || [ md5sum ]).length)
  299. return ok(false);
  300. $.ajax({
  301. url: `/api/media/${encodeURIComponent(md5sum)}/meta/${encodeURIComponent(key)}`,
  302. type: "PATCH",
  303. data: { value: value, list: md5arr },
  304. success: allData => {
  305. allData.forEach(data => {
  306. this.medias = this.medias.filter(x => x.fixedSum !== data.fixedSum);
  307. this.#pushUnique(new Media(data));
  308. });
  309. window.ReloadFilters(this);
  310. ok(true);
  311. },
  312. error: err => ok(false),
  313. });
  314. });
  315. });
  316. }
  317. removeTag(md5sum, tagName) {
  318. let md5arr = undefined;
  319. if (Array.isArray(md5sum)) {
  320. md5arr = md5sum;
  321. md5sum = "list";
  322. }
  323. return LoadingTasks.push(() => {
  324. return new Promise(ok => {
  325. let mediaCount = (md5arr || [ md5sum ]).map(checksum => this.medias.find(x => x.fixedSum === checksum)).filter(x => x.writeAccess).length;
  326. if (mediaCount != (md5arr || [ md5sum ]).length)
  327. return ok(false);
  328. $.ajax({
  329. url: `/api/media/${encodeURIComponent(md5sum)}/tag/del/${encodeURIComponent(tagName)}`,
  330. type: "POST",
  331. data: { list: md5arr || [0] },
  332. success: allData => {
  333. allData.forEach(data => {
  334. let media = this.medias.find(x => x.fixedSum === data.fixedSum);
  335. media.setTags(data.fixedTags, data.tags);
  336. for (let i of data.tags)
  337. this.#pushTag(i, true);
  338. for (let i of data.fixedTags)
  339. this.#pushTag(i, true);
  340. });
  341. ok(true);
  342. },
  343. error: err => ok(false),
  344. });
  345. });
  346. });
  347. }
  348. addTag(md5sum, tagName) {
  349. let md5arr = undefined;
  350. if (Array.isArray(md5sum)) {
  351. md5arr = md5sum;
  352. md5sum = "list";
  353. }
  354. return LoadingTasks.push(() => {
  355. return new Promise(ok => {
  356. let mediaCount = (md5arr || [ md5sum ]).map(checksum => this.medias.find(x => x.fixedSum === checksum)).filter(x => x.writeAccess).length;
  357. if (mediaCount != (md5arr || [ md5sum ]).length)
  358. return ok(false);
  359. $.ajax({
  360. url: `/api/media/${encodeURIComponent(md5sum)}/tag`,
  361. type: "PUT",
  362. data: { tag: tagName, list: md5arr },
  363. success: allData => {
  364. allData.forEach(data => {
  365. let media = this.medias.find(x => x.fixedSum === data.fixedSum);
  366. media.setTags(data.fixedTags, data.tags);
  367. for (let i of data.tags)
  368. this.#pushTag(i, true);
  369. for (let i of data.fixedTags)
  370. this.#pushTag(i, true);
  371. });
  372. ok(true);
  373. },
  374. error: err => ok(false),
  375. });
  376. });
  377. });
  378. }
  379. }
  380. MediaStorage.Instance = new MediaStorage();
  381. setInterval(MediaStorage.Instance.update.bind(MediaStorage.Instance), 60000);