medias.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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.#isLoading = true;
  116. document.getElementById("pch-infiniteScrollLoading").classList.remove("hidden");
  117. let hasData = false;
  118. try {
  119. await LoadingTasks.push(async () => {
  120. let data = await window.indexedData.listMedias();
  121. this.pushAll(data.medias.map(x => new Media(x)));
  122. this.#updateDbVersion(data.version);
  123. this.#isLoading = false;
  124. hasData = !!(data.medias?.length);
  125. });
  126. } catch (err) {
  127. console.error(err);
  128. }
  129. this.downloadMetaList(hasData);
  130. }
  131. #doDownloadMetaList(isUpdate) {
  132. this.#isLoading = true;
  133. document.getElementById("pch-infiniteScrollLoading").classList.remove("hidden");
  134. LoadingTasks.push(() => {
  135. return new Promise(ok => {
  136. let chronology = window.chronology.isInitialized() ? "" : "&chronology"
  137. let oldest = isUpdate !== true ? (this.oldest?.getDateTs() || 0) : 0;
  138. let oldestArg = oldest ? `&from=${oldest}` : "";
  139. let requestCount = 300;
  140. $.get(`/api/media/list?count=${requestCount}${chronology}${oldestArg}&version=${this.#dbVersion}`, data => {
  141. this.pushAll(data.data.map(i => new Media(i)));
  142. if (data.first || data.last)
  143. window.chronology.rebuildRange(data.first, data.last);
  144. if (data.maxVersion)
  145. this.loadingVersion = parseInt(data.maxVersion);
  146. if ((data.data?.length || 0) < requestCount) {
  147. this.#isLoading = false;
  148. this.#updateDbVersion(this.loadingVersion);
  149. window.ReloadFilters(MediaStorage.Instance);
  150. this.dispatchEvent(new CustomEvent("doneLoading"));
  151. document.getElementById("pch-infiniteScrollLoading").classList.add("hidden");
  152. } else {
  153. this.#doDownloadMetaList(false);
  154. }
  155. ok();
  156. });
  157. });
  158. });
  159. }
  160. downloadMetaList(isUpdate) {
  161. if (this.isLoading())
  162. return;
  163. this.#doDownloadMetaList(isUpdate);
  164. }
  165. getDbVersion() { return this.#dbVersion; }
  166. #updateDbVersion(version) {
  167. this.#dbVersion = Math.max(this.#dbVersion, version);
  168. }
  169. #pushMeta(metaKey, metaVal) {
  170. if (metaKey === 'dateTime')
  171. return;
  172. if (!this.allMeta[metaKey])
  173. this.allMeta[metaKey] = new Set();
  174. this.allMeta[metaKey].add(metaVal.value);
  175. if (!this.allMetaTypes[metaKey])
  176. this.allMetaTypes[metaKey] = { type: metaVal.type, canBeEmpty: !!this.medias.length, canWrite: metaVal.canWrite };
  177. }
  178. #pushTag(tag, first) {
  179. while (tag.length && tag.endsWith('/'))
  180. tag = tag.substr(0, tag.length -1);
  181. this.allTags.add(tag);
  182. let index = tag.lastIndexOf('/');
  183. if (index >= 0)
  184. this.#pushTag(tag.substr(0, index));
  185. }
  186. #pushUnique(media) {
  187. for (let i of media.tags)
  188. this.#pushTag(i, true);
  189. for (let i of media.fixedTags)
  190. this.#pushTag(i, true);
  191. for (let key in media.meta)
  192. this.#pushMeta(key, media.meta[key]);
  193. for (let key in this.allMetaTypes)
  194. if (!media.meta[key])
  195. this.allMetaTypes[key].canBeEmpty = true;
  196. this.medias.push(media);
  197. }
  198. #isLoading = false;
  199. isLoading() { return this.#isLoading; }
  200. pushAll(arr, partialLoad) {
  201. let reorder = false;
  202. let newItems = [];
  203. for (let i of arr) {
  204. this.loadingVersion = Math.max(this.loadingVersion, i.version);
  205. if (partialLoad !== true) {
  206. this.oldest = !this.oldest || this.oldest.getDateTs() > i.getDateTs() ? i : this.oldest;
  207. this.newest = !this.newest || this.newest.getDateTs() < i.getDateTs() ? i : this.newest;
  208. }
  209. if (this.medias.length && this.medias[this.medias.length -1].getDateTs() < i.getDateTs())
  210. reorder = true;
  211. let previous = this.medias.find(x => x.fixedSum === i.fixedSum);
  212. if (previous) {
  213. this.medias = this.medias.filter(x => x.fixedSum !== i.fixedSum);
  214. i.ui = previous.ui;
  215. } else {
  216. newItems.push(i);
  217. }
  218. this.#pushUnique(i);
  219. }
  220. for (let i of newItems)
  221. this.dispatchEvent(new CustomEvent("newMedia", { detail: i }));
  222. if (reorder) {
  223. this.medias.sort((a, b) => b.getDateTs() - a.getDateTs());
  224. this.dispatchEvent(new CustomEvent("rebuildMedia"));
  225. }
  226. }
  227. onFilterUpdated() {
  228. this.dispatchEvent(new CustomEvent("rebuildMedia"));
  229. }
  230. getMediaIndex(media) {
  231. return this.medias.indexOf(media);
  232. }
  233. nextMedia(current) {
  234. return this.medias[this.getMediaIndex(current) +1];
  235. }
  236. previousMedia(current) {
  237. return this.medias[this.getMediaIndex(current) -1];
  238. }
  239. getMediaBetweenIndexes(a, b) {
  240. if (a > b)
  241. return this.getMediaBetweenIndexes(b, a);
  242. return this.medias.slice(a, b +1);
  243. }
  244. getMediaBetween(a, b) {
  245. let aIndex = this.medias.indexOf(a);
  246. let bIndex = this.medias.indexOf(b);
  247. if (aIndex < 0 || bIndex < 0 || aIndex === bIndex)
  248. return [];
  249. return this.getMediaBetweenIndexes(aIndex, bIndex);
  250. }
  251. getMediaLocal(md5sum) {
  252. return this.medias.find(x => x.fixedSum === md5sum);
  253. }
  254. async getMedia(md5sum) {
  255. let media = this.medias.find(x => x.fixedSum === md5sum);
  256. if (media)
  257. return media;
  258. return await tryLoadMedia(md5sum);
  259. }
  260. setMetaValue(md5sum, key, value) {
  261. let md5arr = undefined;
  262. if (Array.isArray(md5sum)) {
  263. md5arr = md5sum;
  264. md5sum = "list";
  265. }
  266. return LoadingTasks.push(() => {
  267. return new Promise(ok => {
  268. let mediaCount = (md5arr || [ md5sum ]).map(checksum => this.medias.find(x => x.fixedSum === checksum)).filter(x => x.writeAccess).length;
  269. if (mediaCount != (md5arr || [ md5sum ]).length)
  270. return ok(false);
  271. $.ajax({
  272. url: `/api/media/${encodeURIComponent(md5sum)}/meta/${encodeURIComponent(key)}`,
  273. type: "PATCH",
  274. data: { value: value, list: md5arr },
  275. success: allData => {
  276. allData.forEach(data => {
  277. let media = this.medias.find(x => x.fixedSum === data.fixedSum);
  278. let meta = data.meta[key] || { type: 'string', value: value, canWrite: true };
  279. meta.value = value;
  280. this.#pushMeta(key, meta);
  281. media.meta[key] = meta;
  282. });
  283. window.ReloadFilters(this);
  284. ok(true);
  285. },
  286. error: err => ok(false),
  287. });
  288. });
  289. });
  290. }
  291. removeTag(md5sum, tagName) {
  292. let md5arr = undefined;
  293. if (Array.isArray(md5sum)) {
  294. md5arr = md5sum;
  295. md5sum = "list";
  296. }
  297. return LoadingTasks.push(() => {
  298. return new Promise(ok => {
  299. let mediaCount = (md5arr || [ md5sum ]).map(checksum => this.medias.find(x => x.fixedSum === checksum)).filter(x => x.writeAccess).length;
  300. if (mediaCount != (md5arr || [ md5sum ]).length)
  301. return ok(false);
  302. $.ajax({
  303. url: `/api/media/${encodeURIComponent(md5sum)}/tag/del/${encodeURIComponent(tagName)}`,
  304. type: "POST",
  305. data: { list: md5arr || [0] },
  306. success: allData => {
  307. allData.forEach(data => {
  308. let media = this.medias.find(x => x.fixedSum === data.fixedSum);
  309. media.setTags(data.fixedTags, data.tags);
  310. for (let i of data.tags)
  311. this.#pushTag(i, true);
  312. for (let i of data.fixedTags)
  313. this.#pushTag(i, true);
  314. });
  315. ok(true);
  316. },
  317. error: err => ok(false),
  318. });
  319. });
  320. });
  321. }
  322. addTag(md5sum, tagName) {
  323. let md5arr = undefined;
  324. if (Array.isArray(md5sum)) {
  325. md5arr = md5sum;
  326. md5sum = "list";
  327. }
  328. return LoadingTasks.push(() => {
  329. return new Promise(ok => {
  330. let mediaCount = (md5arr || [ md5sum ]).map(checksum => this.medias.find(x => x.fixedSum === checksum)).filter(x => x.writeAccess).length;
  331. if (mediaCount != (md5arr || [ md5sum ]).length)
  332. return ok(false);
  333. $.ajax({
  334. url: `/api/media/${encodeURIComponent(md5sum)}/tag`,
  335. type: "PUT",
  336. data: { tag: tagName, list: md5arr },
  337. success: allData => {
  338. allData.forEach(data => {
  339. let media = this.medias.find(x => x.fixedSum === data.fixedSum);
  340. media.setTags(data.fixedTags, data.tags);
  341. for (let i of data.tags)
  342. this.#pushTag(i, true);
  343. for (let i of data.fixedTags)
  344. this.#pushTag(i, true);
  345. });
  346. ok(true);
  347. },
  348. error: err => ok(false),
  349. });
  350. });
  351. });
  352. }
  353. }
  354. MediaStorage.Instance = new MediaStorage();
  355. setInterval(MediaStorage.Instance.update.bind(MediaStorage.Instance), 60000);