1
0

medias.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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.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. rebuildMetaList() {
  85. this.#reset();
  86. this.dispatchEvent(new CustomEvent("rebuildMedia"));
  87. window.chronology.reset();
  88. this.downloadMetaList();
  89. }
  90. update() {
  91. this.downloadMetaList(true);
  92. }
  93. downloadMetaList(isUpdate) {
  94. if (this.isLoading())
  95. return;
  96. this.#isLoading = true;
  97. document.getElementById("pch-infiniteScrollLoading").classList.remove("hidden");
  98. LoadingTasks.push(() => {
  99. return new Promise(ok => {
  100. let chronology = window.chronology.isInitialized() ? "" : "&chronology"
  101. let oldest = isUpdate !== true ? (this.oldest?.date?.getTime() || 0) : 0;
  102. let oldestArg = oldest ? `&from=${oldest}` : "";
  103. let requestCount = 300;
  104. $.get(`/api/media/list?count=${requestCount}${chronology}${oldestArg}&version=${this.dbVersion}`, data => {
  105. this.pushAll(data.data.map(i => new Media(i)));
  106. if (data.first || data.last)
  107. window.chronology.rebuildRange(data.first, data.last);
  108. this.#isLoading = false;
  109. if ((data.data?.length || 0) < requestCount) {
  110. document.getElementById("pch-infiniteScrollLoading").classList.add("hidden");
  111. this.dbVersion = Math.max(this.dbVersion, this.loadingVersion);
  112. window.ReloadFilters(MediaStorage.Instance);
  113. }
  114. else
  115. setTimeout(this.downloadMetaList.bind(this, isUpdate), 25);
  116. ok();
  117. });
  118. });
  119. });
  120. }
  121. #pushMeta(metaKey, metaVal) {
  122. if (metaKey === 'dateTime')
  123. return;
  124. if (!this.allMeta[metaKey])
  125. this.allMeta[metaKey] = new Set();
  126. this.allMeta[metaKey].add(metaVal.value);
  127. if (!this.allMetaTypes[metaKey])
  128. this.allMetaTypes[metaKey] = { type: metaVal.type, canBeEmpty: !!this.medias.length, canWrite: metaVal.canWrite };
  129. }
  130. #pushTag(tag, first) {
  131. while (tag.length && tag.endsWith('/'))
  132. tag = tag.substr(0, tag.length -1);
  133. this.allTags.add(tag);
  134. let index = tag.lastIndexOf('/');
  135. if (index >= 0)
  136. this.#pushTag(tag.substr(0, index));
  137. }
  138. #pushUnique(media) {
  139. for (let i of media.tags)
  140. this.#pushTag(i, true);
  141. for (let i of media.fixedTags)
  142. this.#pushTag(i, true);
  143. for (let key in media.meta)
  144. this.#pushMeta(key, media.meta[key]);
  145. for (let key in this.allMetaTypes)
  146. if (!media.meta[key])
  147. this.allMetaTypes[key].canBeEmpty = true;
  148. this.medias.push(media);
  149. }
  150. #isLoading = false;
  151. isLoading() { return this.#isLoading; }
  152. pushAll(arr, partialLoad) {
  153. let reorder = false;
  154. let newItems = [];
  155. for (let i of arr) {
  156. this.loadingVersion = Math.max(this.loadingVersion, i.version);
  157. if (partialLoad !== true) {
  158. this.oldest = !this.oldest || this.oldest.date.getTime() > i.date.getTime() ? i : this.oldest;
  159. this.newest = !this.newest || this.newest.date.getTime() < i.date.getTime() ? i : this.newest;
  160. }
  161. if (this.medias.length && this.medias[this.medias.length -1].date.getTime() < i.date.getTime())
  162. reorder = true;
  163. let previous = this.medias.find(x => x.fixedSum === i.fixedSum);
  164. if (previous) {
  165. this.medias = this.medias.filter(x => x.fixedSum !== i.fixedSum);
  166. i.ui = previous.ui;
  167. } else {
  168. newItems.push(i);
  169. }
  170. this.#pushUnique(i);
  171. }
  172. for (let i of newItems)
  173. this.dispatchEvent(new CustomEvent("newMedia", { detail: i }));
  174. if (reorder) {
  175. this.medias.sort((a, b) => b.date.getTime() - a.date.getTime());
  176. this.dispatchEvent(new CustomEvent("rebuildMedia"));
  177. }
  178. }
  179. onFilterUpdated() {
  180. this.dispatchEvent(new CustomEvent("rebuildMedia"));
  181. }
  182. getMediaIndex(media) {
  183. return this.medias.indexOf(media);
  184. }
  185. nextMedia(current) {
  186. return this.medias[this.getMediaIndex(current) +1];
  187. }
  188. previousMedia(current) {
  189. return this.medias[this.getMediaIndex(current) -1];
  190. }
  191. getMediaBetweenIndexes(a, b) {
  192. if (a > b)
  193. return this.getMediaBetweenIndexes(b, a);
  194. return this.medias.slice(a, b +1);
  195. }
  196. getMediaBetween(a, b) {
  197. let aIndex = this.medias.indexOf(a);
  198. let bIndex = this.medias.indexOf(b);
  199. if (aIndex < 0 || bIndex < 0 || aIndex === bIndex)
  200. return [];
  201. return this.getMediaBetweenIndexes(aIndex, bIndex);
  202. }
  203. getMediaLocal(md5sum) {
  204. return this.medias.find(x => x.fixedSum === md5sum);
  205. }
  206. async getMedia(md5sum) {
  207. let media = this.medias.find(x => x.fixedSum === md5sum);
  208. if (media)
  209. return media;
  210. return await tryLoadMedia(md5sum);
  211. }
  212. setMetaValue(md5sum, key, value) {
  213. let md5arr = undefined;
  214. if (Array.isArray(md5sum)) {
  215. md5arr = md5sum;
  216. md5sum = "list";
  217. }
  218. return LoadingTasks.push(() => {
  219. return new Promise(ok => {
  220. let mediaCount = (md5arr || [ md5sum ]).map(checksum => this.medias.find(x => x.fixedSum === checksum)).filter(x => x.writeAccess).length;
  221. if (mediaCount != (md5arr || [ md5sum ]).length)
  222. return ok(false);
  223. $.ajax({
  224. url: `/api/media/${encodeURIComponent(md5sum)}/meta/${encodeURIComponent(key)}`,
  225. type: "PATCH",
  226. data: { value: value, list: md5arr },
  227. success: allData => {
  228. allData.forEach(data => {
  229. let media = this.medias.find(x => x.fixedSum === data.fixedSum);
  230. let meta = data.meta[key] || { type: 'string', value: value, canWrite: true };
  231. meta.value = value;
  232. this.#pushMeta(key, meta);
  233. media.meta[key] = meta;
  234. });
  235. window.ReloadFilters(this);
  236. ok(true);
  237. },
  238. error: err => ok(false),
  239. });
  240. });
  241. });
  242. }
  243. removeTag(md5sum, tagName) {
  244. let md5arr = undefined;
  245. if (Array.isArray(md5sum)) {
  246. md5arr = md5sum;
  247. md5sum = "list";
  248. }
  249. return LoadingTasks.push(() => {
  250. return new Promise(ok => {
  251. let mediaCount = (md5arr || [ md5sum ]).map(checksum => this.medias.find(x => x.fixedSum === checksum)).filter(x => x.writeAccess).length;
  252. if (mediaCount != (md5arr || [ md5sum ]).length)
  253. return ok(false);
  254. $.ajax({
  255. url: `/api/media/${encodeURIComponent(md5sum)}/tag/del/${encodeURIComponent(tagName)}`,
  256. type: "POST",
  257. data: { list: md5arr || [0] },
  258. success: allData => {
  259. allData.forEach(data => {
  260. let media = this.medias.find(x => x.fixedSum === data.fixedSum);
  261. media.setTags(data.fixedTags, data.tags);
  262. for (let i of data.tags)
  263. this.#pushTag(i, true);
  264. for (let i of data.fixedTags)
  265. this.#pushTag(i, true);
  266. });
  267. ok(true);
  268. },
  269. error: err => ok(false),
  270. });
  271. });
  272. });
  273. }
  274. addTag(md5sum, tagName) {
  275. let md5arr = undefined;
  276. if (Array.isArray(md5sum)) {
  277. md5arr = md5sum;
  278. md5sum = "list";
  279. }
  280. return LoadingTasks.push(() => {
  281. return new Promise(ok => {
  282. let mediaCount = (md5arr || [ md5sum ]).map(checksum => this.medias.find(x => x.fixedSum === checksum)).filter(x => x.writeAccess).length;
  283. if (mediaCount != (md5arr || [ md5sum ]).length)
  284. return ok(false);
  285. $.ajax({
  286. url: `/api/media/${encodeURIComponent(md5sum)}/tag`,
  287. type: "PUT",
  288. data: { tag: tagName, list: md5arr },
  289. success: allData => {
  290. allData.forEach(data => {
  291. let media = this.medias.find(x => x.fixedSum === data.fixedSum);
  292. media.setTags(data.fixedTags, data.tags);
  293. for (let i of data.tags)
  294. this.#pushTag(i, true);
  295. for (let i of data.fixedTags)
  296. this.#pushTag(i, true);
  297. });
  298. ok(true);
  299. },
  300. error: err => ok(false),
  301. });
  302. });
  303. });
  304. }
  305. }
  306. MediaStorage.Instance = new MediaStorage();
  307. setInterval(MediaStorage.Instance.update.bind(MediaStorage.Instance), 60000);