1
0

medias.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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.#reset();
  64. }
  65. #reset() {
  66. this.allMeta = {};
  67. this.allMetaTypes = {};
  68. this.allTags = new Set();
  69. this.medias = [];
  70. this.oldest = null;
  71. this.newest = null;
  72. }
  73. rebuildMetaList() {
  74. this.#reset();
  75. window.chronology.reset();
  76. this.downloadMetaList();
  77. }
  78. downloadMetaList() {
  79. if (this.isLoading())
  80. return;
  81. this.#isLoading = true;
  82. LoadingTasks.push(() => {
  83. return new Promise(ok => {
  84. let chronology = window.chronology.isInitialized() ? "" : "&chronology"
  85. let oldest = (this.oldest?.date?.getTime() || 0);
  86. let oldestArg = oldest ? `&from=${oldest}` : "";
  87. let requestCount = 300;
  88. $.get(`/api/media/list?count=${requestCount}${chronology}${oldestArg}`, data => {
  89. this.pushAll(data.data.map(i => new Media(i)));
  90. if (data.first || data.last)
  91. window.chronology.rebuildRange(data.first, data.last);
  92. this.#isLoading = false;
  93. if ((data.data?.length || 0) < requestCount) {
  94. document.getElementById("pch-infiniteScrollLoading").classList.add("hidden");
  95. window.ReloadFilters(MediaStorage.Instance);
  96. }
  97. else
  98. setTimeout(this.downloadMetaList.bind(this), 25);
  99. ok();
  100. });
  101. });
  102. });
  103. }
  104. #pushMeta(metaKey, metaVal) {
  105. if (metaKey === 'dateTime')
  106. return;
  107. if (!this.allMeta[metaKey])
  108. this.allMeta[metaKey] = new Set();
  109. this.allMeta[metaKey].add(metaVal.value);
  110. if (!this.allMetaTypes[metaKey])
  111. this.allMetaTypes[metaKey] = { type: metaVal.type, canBeEmpty: !!this.medias.length, canWrite: metaVal.canWrite };
  112. }
  113. #pushTag(tag, first) {
  114. while (tag.length && tag.endsWith('/'))
  115. tag = tag.substr(0, tag.length -1);
  116. this.allTags.add(tag);
  117. let index = tag.lastIndexOf('/');
  118. if (index >= 0)
  119. this.#pushTag(tag.substr(0, index));
  120. }
  121. #pushUnique(media) {
  122. for (let i of media.tags)
  123. this.#pushTag(i, true);
  124. for (let i of media.fixedTags)
  125. this.#pushTag(i, true);
  126. for (let key in media.meta)
  127. this.#pushMeta(key, media.meta[key]);
  128. for (let key in this.allMetaTypes)
  129. if (!media.meta[key])
  130. this.allMetaTypes[key].canBeEmpty = true;
  131. this.medias.push(media);
  132. }
  133. #isLoading = false;
  134. isLoading() { return this.#isLoading; }
  135. pushAll(arr, partialLoad) {
  136. let result = [];
  137. let reorder = false;
  138. for (let i of arr) {
  139. if (partialLoad !== true) {
  140. this.oldest = !this.oldest || this.oldest.date.getTime() > i.date.getTime() ? i : this.oldest;
  141. this.newest = !this.newest || this.newest.date.getTime() < i.date.getTime() ? i : this.newest;
  142. }
  143. if (this.medias.length && this.medias[this.medias.length -1].date.getTime() < i.date.getTime())
  144. reorder = true;
  145. if (this.medias.find(x => x.fixedSum === i.fixedSum))
  146. continue;
  147. this.#pushUnique(i);
  148. result.push(i);
  149. }
  150. for (let i of result)
  151. this.dispatchEvent(new CustomEvent("newMedia", { detail: i }));
  152. if (reorder) {
  153. this.medias.sort((a, b) => b.date.getTime() - a.date.getTime());
  154. this.dispatchEvent(new CustomEvent("rebuildMedia"));
  155. }
  156. }
  157. onFilterUpdated() {
  158. this.dispatchEvent(new CustomEvent("rebuildMedia"));
  159. }
  160. getMediaIndex(media) {
  161. return this.medias.indexOf(media);
  162. }
  163. nextMedia(current) {
  164. return this.medias[this.getMediaIndex(current) +1];
  165. }
  166. previousMedia(current) {
  167. return this.medias[this.getMediaIndex(current) -1];
  168. }
  169. getMediaBetweenIndexes(a, b) {
  170. if (a > b)
  171. return this.getMediaBetweenIndexes(b, a);
  172. return this.medias.slice(a, b +1);
  173. }
  174. getMediaBetween(a, b) {
  175. let aIndex = this.medias.indexOf(a);
  176. let bIndex = this.medias.indexOf(b);
  177. if (aIndex < 0 || bIndex < 0 || aIndex === bIndex)
  178. return [];
  179. return this.getMediaBetweenIndexes(aIndex, bIndex);
  180. }
  181. getMediaLocal(md5sum) {
  182. return this.medias.find(x => x.fixedSum === md5sum);
  183. }
  184. async getMedia(md5sum) {
  185. let media = this.medias.find(x => x.fixedSum === md5sum);
  186. if (media)
  187. return media;
  188. return await tryLoadMedia(md5sum);
  189. }
  190. setMetaValue(md5sum, key, value) {
  191. return LoadingTasks.push(() => {
  192. return new Promise(ok => {
  193. let media = this.medias.find(x => x.fixedSum === md5sum);
  194. if (!media || !media.writeAccess)
  195. return ok(false);
  196. $.ajax({
  197. url: `/api/media/${encodeURIComponent(md5sum)}/meta/${encodeURIComponent(key)}`,
  198. type: "PATCH",
  199. data: { value },
  200. success: (media) => {
  201. let meta = media.meta[key] || { type: 'string', value: value, canWrite: true };
  202. meta.value = value;
  203. this.#pushMeta(key, meta);
  204. media.meta[key] = meta;
  205. window.ReloadFilters(this);
  206. ok(true);
  207. },
  208. error: err => ok(false),
  209. });
  210. });
  211. });
  212. }
  213. removeTag(md5sum, tagName) {
  214. return LoadingTasks.push(() => {
  215. return new Promise(ok => {
  216. let media = this.medias.find(x => x.fixedSum === md5sum);
  217. if (!media || !media.writeAccess)
  218. return ok(false);
  219. $.ajax({
  220. url: `/api/media/${encodeURIComponent(md5sum)}/tag/${encodeURIComponent(tagName)}`,
  221. type: "DELETE",
  222. success: data => {
  223. media.setTags(data.fixedTags, data.tags);
  224. for (let i of data.tags)
  225. this.#pushTag(i, true);
  226. for (let i of data.fixedTags)
  227. this.#pushTag(i, true);
  228. ok(true);
  229. },
  230. error: err => ok(false),
  231. });
  232. });
  233. });
  234. }
  235. addTag(md5sum, tagName) {
  236. return LoadingTasks.push(() => {
  237. return new Promise(ok => {
  238. let media = this.medias.find(x => x.fixedSum === md5sum);
  239. if (!media || !media.writeAccess)
  240. return ok(false);
  241. $.ajax({
  242. url: `/api/media/${encodeURIComponent(md5sum)}/tag`,
  243. type: "PUT",
  244. data: { tag: tagName },
  245. success: data => {
  246. media.setTags(data.fixedTags, data.tags);
  247. for (let i of data.tags)
  248. this.#pushTag(i, true);
  249. for (let i of data.fixedTags)
  250. this.#pushTag(i, true);
  251. ok(true);
  252. },
  253. error: err => ok(false),
  254. });
  255. });
  256. });
  257. }
  258. }
  259. MediaStorage.Instance = new MediaStorage();