medias.js 13 KB

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