medias.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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.tags = [];
  11. this.writeAccess = data.accessType === 2;
  12. this.thumbnail = `/api/media/thumbnail/${data.fixedSum}.jpg`;
  13. this.original = `/api/media/original/${data.fixedSum}`;
  14. this.ui = null;
  15. this.setTags(data.fixedTags || [], data.tags || []);
  16. for (let i in this.meta) {
  17. if (this.meta[i].type === 'date')
  18. this.meta[i].value = new Date(parseInt(this.meta[i].value));
  19. else if (this.meta[i].type === 'number' || this.meta[i].type === 'octet')
  20. this.meta[i].value = parseInt(this.meta[i].value);
  21. else if (this.meta[i].type === 'string')
  22. this.meta[i].value = '' + this.meta[i].value;
  23. }
  24. }
  25. resize(maxWidth, maxHeight) {
  26. let ratio = Math.min(1, Math.max(
  27. maxWidth / (this.meta?.width?.value || maxWidth),
  28. maxHeight / (this.meta?.height?.value || maxHeight)));
  29. let result = {
  30. width: Math.floor(this.meta.width?.value *ratio),
  31. height: Math.floor(this.meta.height?.value *ratio),
  32. };
  33. if (isNaN(result.width) || isNaN(result.height) || !result.height || !result.width) {
  34. console.error("Failed to resize image ", this);
  35. return null;
  36. }
  37. return result;
  38. }
  39. setTags(fixedTags, tags) {
  40. this.tags = tags.reduce((acc, tag) => { acc.add(tag.replaceAll(/\/\/+/gi, '/')); return acc; }, new Set());
  41. this.fixedTags = fixedTags.reduce((acc, tag) => { acc.add(tag.replaceAll(/\/\/+/gi, '/')); return acc; }, new Set());
  42. }
  43. allTags() {
  44. return Array.from(new Set([...this.fixedTags, ...this.tags])).sort();
  45. }
  46. }
  47. function tryLoadMedia(md5sum) {
  48. return new Promise((ok, ko) => {
  49. $.get("/api/media/" +md5sum, data => {
  50. let item = new Media(data);
  51. MediaStorage.Instance.pushAll([item], true);
  52. ok(item);
  53. }).fail(err => {
  54. console.error("Trying to get media with md5sum " +md5sum +" failed:", err.responseText);
  55. ok(null);
  56. });
  57. });
  58. }
  59. class MediaStorage extends EventTarget
  60. {
  61. constructor() {
  62. super();
  63. this.allMeta = {};
  64. this.allMetaTypes = {};
  65. this.allTags = new Set();
  66. this.medias = [];
  67. this.oldest = null;
  68. this.newest = null;
  69. }
  70. downloadMetaList() {
  71. if (this.isLoading())
  72. return;
  73. this.#isLoading = true;
  74. LoadingTasks.push(() => {
  75. return new Promise(ok => {
  76. let chronology = window.chronology.isInitialized() ? "" : "&chronology"
  77. let oldest = (this.oldest?.date?.getTime() || 0);
  78. let oldestArg = oldest ? `&from=${oldest}` : "";
  79. let requestCount = 300;
  80. $.get(`/api/media/list?count=${requestCount}${chronology}${oldestArg}`, data => {
  81. this.pushAll(data.data.map(i => new Media(i)));
  82. if (data.first || data.last)
  83. window.chronology.rebuildRange(data.first, data.last);
  84. this.#isLoading = false;
  85. if ((data.data?.length || 0) < requestCount) {
  86. document.getElementById("pch-infiniteScrollLoading").classList.add("hidden");
  87. window.ReloadFilters(MediaStorage.Instance);
  88. }
  89. else
  90. setTimeout(this.downloadMetaList.bind(this), 25);
  91. ok();
  92. });
  93. });
  94. });
  95. }
  96. #pushMeta(metaKey, metaVal) {
  97. if (metaKey === 'dateTime')
  98. return;
  99. if (!this.allMeta[metaKey])
  100. this.allMeta[metaKey] = new Set();
  101. this.allMeta[metaKey].add(metaVal.value);
  102. if (!this.allMetaTypes[metaKey])
  103. this.allMetaTypes[metaKey] = { type: metaVal.type, canBeEmpty: !!this.medias.length, canWrite: metaVal.canWrite };
  104. }
  105. #pushTag(tag, first) {
  106. while (tag.length && tag.endsWith('/'))
  107. tag = tag.substr(0, tag.length -1);
  108. this.allTags.add(tag);
  109. let index = tag.lastIndexOf('/');
  110. if (index >= 0)
  111. this.#pushTag(tag.substr(0, index));
  112. }
  113. #pushUnique(media) {
  114. for (let i of media.tags)
  115. this.#pushTag(i, true);
  116. for (let i of media.fixedTags)
  117. this.#pushTag(i, true);
  118. for (let key in media.meta)
  119. this.#pushMeta(key, media.meta[key]);
  120. for (let key in this.allMetaTypes)
  121. if (!media.meta[key])
  122. this.allMetaTypes[key].canBeEmpty = true;
  123. this.medias.push(media);
  124. }
  125. #isLoading = false;
  126. isLoading() { return this.#isLoading; }
  127. pushAll(arr, partialLoad) {
  128. let result = [];
  129. let reorder = false;
  130. for (let i of arr) {
  131. if (partialLoad !== true) {
  132. this.oldest = !this.oldest || this.oldest.date.getTime() > i.date.getTime() ? i : this.oldest;
  133. this.newest = !this.newest || this.newest.date.getTime() < i.date.getTime() ? i : this.newest;
  134. }
  135. if (this.medias.length && this.medias[this.medias.length -1].date.getTime() < i.date.getTime())
  136. reorder = true;
  137. if (this.medias.find(x => x.fixedSum === i.fixedSum))
  138. continue;
  139. this.#pushUnique(i);
  140. result.push(i);
  141. }
  142. for (let i of result)
  143. this.dispatchEvent(new CustomEvent("newMedia", { detail: i }));
  144. if (reorder) {
  145. this.medias.sort((a, b) => b.date.getTime() - a.date.getTime());
  146. this.dispatchEvent(new CustomEvent("rebuildMedia"));
  147. }
  148. }
  149. onFilterUpdated() {
  150. this.dispatchEvent(new CustomEvent("rebuildMedia"));
  151. }
  152. getMediaIndex(media) {
  153. return this.medias.indexOf(media);
  154. }
  155. nextMedia(current) {
  156. return this.medias[this.getMediaIndex(current) +1];
  157. }
  158. previousMedia(current) {
  159. return this.medias[this.getMediaIndex(current) -1];
  160. }
  161. getMediaBetweenIndexes(a, b) {
  162. if (a > b)
  163. return this.getMediaBetweenIndexes(b, a);
  164. return this.medias.slice(a, b +1);
  165. }
  166. getMediaBetween(a, b) {
  167. let aIndex = this.medias.indexOf(a);
  168. let bIndex = this.medias.indexOf(b);
  169. if (aIndex < 0 || bIndex < 0 || aIndex === bIndex)
  170. return [];
  171. return this.getMediaBetweenIndexes(aIndex, bIndex);
  172. }
  173. getMediaLocal(md5sum) {
  174. return this.medias.find(x => x.fixedSum === md5sum);
  175. }
  176. async getMedia(md5sum) {
  177. let media = this.medias.find(x => x.fixedSum === md5sum);
  178. if (media)
  179. return media;
  180. return await tryLoadMedia(md5sum);
  181. }
  182. setMetaValue(md5sum, key, value) {
  183. return LoadingTasks.push(() => {
  184. return new Promise(ok => {
  185. let media = this.medias.find(x => x.fixedSum === md5sum);
  186. if (!media || !media.writeAccess)
  187. return ok(false);
  188. $.ajax({
  189. url: `/api/media/${encodeURIComponent(md5sum)}/meta/${encodeURIComponent(key)}`,
  190. type: "PATCH",
  191. data: { value },
  192. success: (media) => {
  193. let meta = media.meta[key] || { type: 'string', value: value, canWrite: true };
  194. meta.value = value;
  195. this.#pushMeta(key, meta);
  196. media.meta[key] = meta;
  197. window.ReloadFilters(this);
  198. ok(true);
  199. },
  200. error: err => ok(false),
  201. });
  202. });
  203. });
  204. }
  205. removeTag(md5sum, tagName) {
  206. return LoadingTasks.push(() => {
  207. return new Promise(ok => {
  208. let media = this.medias.find(x => x.fixedSum === md5sum);
  209. if (!media || !media.writeAccess)
  210. return ok(false);
  211. $.ajax({
  212. url: `/api/media/${encodeURIComponent(md5sum)}/tag/${encodeURIComponent(tagName)}`,
  213. type: "DELETE",
  214. success: data => {
  215. media.setTags(data.fixedTags, data.tags);
  216. for (let i of data.tags)
  217. this.#pushTag(i, true);
  218. for (let i of data.fixedTags)
  219. this.#pushTag(i, true);
  220. ok(true);
  221. },
  222. error: err => ok(false),
  223. });
  224. });
  225. });
  226. }
  227. addTag(md5sum, tagName) {
  228. return LoadingTasks.push(() => {
  229. return new Promise(ok => {
  230. let media = this.medias.find(x => x.fixedSum === md5sum);
  231. if (!media || !media.writeAccess)
  232. return ok(false);
  233. $.ajax({
  234. url: `/api/media/${encodeURIComponent(md5sum)}/tag`,
  235. type: "PUT",
  236. data: { tag: tagName },
  237. success: data => {
  238. media.setTags(data.fixedTags, data.tags);
  239. for (let i of data.tags)
  240. this.#pushTag(i, true);
  241. for (let i of data.fixedTags)
  242. this.#pushTag(i, true);
  243. ok(true);
  244. },
  245. error: err => ok(false),
  246. });
  247. });
  248. });
  249. }
  250. }
  251. MediaStorage.Instance = new MediaStorage();