medias.js 14 KB

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