Camamba Users Search Library

fetches Users

当前为 2022-12-28 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/446634/1132465/Camamba%20Users%20Search%20Library.js

  1. // ==UserScript==
  2. // @name Camamba Users Search Library
  3. // @namespace hoehleg.userscripts.private
  4. // @version 0.0.8
  5. // @description fetches Users
  6. // @author Gerrit Höhle
  7. // @license MIT
  8. //
  9. // @require https://greasyfork.org/scripts/405144-httprequest/code/HttpRequest.js?version=1063408
  10. //
  11. // @grant GM_xmlhttpRequest
  12. // ==/UserScript==
  13.  
  14. // https://greasyfork.org/scripts/446634-camamba-users-search-library/
  15.  
  16. /* jslint esversion: 11 */
  17.  
  18. /**
  19. * @typedef {object} UserParams
  20. * @property {string} name
  21. * @property {uid} [number]
  22. * @property {'male'|'female'|'couple'?} [gender]
  23. * @property {number} [age]
  24. * @property {number} [level]
  25. * @property {number} [longitude]
  26. * @property {number} [latitude]
  27. * @property {string} [location]
  28. * @property {number} [distanceKM]
  29. * @property {boolean} [isReal]
  30. * @property {boolean} [hasPremium]
  31. * @property {boolean} [hasSuper]
  32. * @property {boolean} [isPerma]
  33. * @property {boolean} [isOnline]
  34. * @property {string} [room]
  35. * @property {Date} [lastSeen]
  36. * @property {Date} [regDate]
  37. * @property {string[]} [ipList]
  38. * @property {Date} [scorePassword]
  39. * @property {Date} [scoreFinal]
  40. * @property {(date: Date) => string} [dateToHumanReadable]
  41. */
  42.  
  43. const GuessLogSearch = (() => {
  44. const cache = {};
  45. const maxHoursInCache = 1;
  46.  
  47. return class GuessLogSearch extends HttpRequestHtml {
  48.  
  49. constructor(name) {
  50. /**
  51. * @param {string} labelText
  52. * @param {string} textContent
  53. * @returns {number}
  54. */
  55. const matchScore = (labelText, textContent) => {
  56. const regexLookBehind = new RegExp("(?<=" + labelText + ":\\s)");
  57. const regexFloat = /\d{1,2}\.?\d{0,20}/;
  58. const regexLookAhead = /(?=\spoints)/;
  59.  
  60. for (const regexesToJoin of [
  61. [regexLookBehind, regexFloat, regexLookAhead],
  62. [regexLookBehind, regexFloat]
  63. ]) {
  64. const regexAsString = regexesToJoin.map(re => re.source).join("");
  65. const matcher = new RegExp(regexAsString, "i").exec(textContent);
  66. if (matcher != null) {
  67. return Number.parseFloat(matcher[0]);
  68. }
  69. }
  70. };
  71.  
  72. /**
  73. * @param {RegExp} regex
  74. * @param {string} textContent
  75. * @returns {Array<String>}
  76. */
  77. const matchList = (regex, textContent) => {
  78. const results = [...textContent.matchAll(regex)].reduce((a, b) => [...a, ...b], []);
  79. if (results.length) {
  80. const resultsDistinct = [...new Set(results)];
  81. return resultsDistinct;
  82. }
  83. };
  84.  
  85. super({
  86. url: 'https://www.camamba.com/guesslog.php',
  87. params: { name },
  88. resultTransformer: (resp) => {
  89. const textContent = resp.html.body.textContent;
  90.  
  91. const ipList = matchList(/(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])/g, textContent);
  92. const prints = matchList(/(?<=Print\d{0,2}\schecked\sis\s)[0-9a-f]+/g, textContent);
  93.  
  94. const scorePassword = matchScore("password check", textContent);
  95. const scoreFinal = matchScore("final score", textContent);
  96.  
  97. return { userName: name, ipList, prints, scorePassword, scoreFinal };
  98. }
  99. });
  100. }
  101.  
  102. /** @returns {Promise<GuessLog>} */
  103. async send() {
  104. const key = `ugls_${this.params.uid}`;
  105. let result = cache[this.params.uid] || JSON.parse(await GM.getValue(key, "{}"));
  106. const timeStamp = result?.timeStamp;
  107.  
  108. if (!timeStamp || new Date().getTime() - timeStamp >= maxHoursInCache * 60 * 60 * 1000) {
  109. result = await super.send();
  110.  
  111. cache[this.params.uid] = result;
  112. GM.setValue(key, JSON.stringify(result));
  113. }
  114.  
  115. return result;
  116. }
  117.  
  118. /**
  119. * @param {string} name
  120. * @returns {Promise<GuessLog>}
  121. */
  122. static async send(name) {
  123. return await new GuessLogSearch(name).send();
  124. }
  125. }
  126. })();
  127.  
  128. /**
  129. * @typedef {Object} BanLog
  130. * @property {string} moderator - user or moderator who triggered the log
  131. * @property {string} user - user who is subject
  132. * @property {Date} date - date of this log
  133. * @property {string} reason - content
  134. */
  135.  
  136. class BannLogSearch extends HttpRequestHtml {
  137. /**
  138. * @param {number} uid
  139. */
  140. constructor(uid = null) {
  141. super({
  142. url: 'https://www.camamba.com/banlog.php',
  143. params: uid ? { admin: uid } : {},
  144. resultTransformer: (response, _request) => {
  145. const results = [];
  146. const xPathExpr = "//tr" + ['User', 'Moderator', 'Date', 'Reason'].map(hdrText => `[td[span[text()='${hdrText}']]]`).join("");
  147. let tr = (response.html.evaluate(xPathExpr, response.html.body, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue || {}).nextElementSibling;
  148.  
  149. while (tr) {
  150. const tds = tr.querySelectorAll('td');
  151. const user = tds[0].querySelector("a") || tds[0].textContent;
  152. const moderator = tds[1].textContent;
  153.  
  154. let date;
  155. const dateMatch = /(\d{2}).(\d{2}).(\d{4})<br>(\d{1,2}):(\d{2}):(\d{2})/.exec(tds[2].innerHTML);
  156. if (dateMatch) {
  157. const day = dateMatch[1];
  158. const month = dateMatch[2];
  159. const year = dateMatch[3];
  160. const hour = dateMatch[4];
  161. const minute = dateMatch[5];
  162. const second = dateMatch[6];
  163. date = new Date(year, month - 1, day, hour, minute, second);
  164. }
  165.  
  166. const reason = tds[3].textContent;
  167. results.push({ user, moderator, date, reason });
  168.  
  169. tr = tr.nextElementSibling;
  170. }
  171.  
  172. return results;
  173. }
  174. });
  175. }
  176.  
  177. /**
  178. * @param {number} uid
  179. * @returns {Promise<BanLog[]>}
  180. */
  181. static async send(uid) {
  182. return await new BannLogSearch(uid).send();
  183. }
  184. }
  185.  
  186. class GalleryImage {
  187. constructor({ dataURI, href }) {
  188. /** @type {string} */
  189. this.dataURI = dataURI;
  190. /** @type {string} */
  191. this.href = href;
  192. }
  193. }
  194.  
  195.  
  196. class UserLevel {
  197. constructor({ level, uid = null, name = null, timeStamp = null }) {
  198.  
  199. /** @type {number} */
  200. this.level = level !== null ? Number.parseInt(level) : null;
  201.  
  202. /** @type {number} */
  203. this.uid = uid !== null ? Number.parseInt(uid) : null;
  204.  
  205. /** @type {string} */
  206. this.name = name;
  207.  
  208. /** @type {number} */
  209. this.timeStamp = timeStamp !== null ? Number.parseInt(timeStamp) : null;
  210. }
  211. }
  212.  
  213. const UserLevelSearch = (() => {
  214. const cache = {};
  215. const maxHoursInCache = 24;
  216.  
  217. return class UserLevelSearch extends HttpRequestHtml {
  218. constructor(uid) {
  219. super({
  220. url: 'https://www.camamba.com/user_level.php',
  221. params: { uid },
  222. resultTransformer: (response, request) => {
  223. const html = response.html;
  224.  
  225. let name = null, level = null;
  226.  
  227. const nameElement = html.querySelector('b');
  228. if (nameElement) {
  229. name = nameElement.textContent;
  230. }
  231.  
  232. const levelElement = html.querySelector('font.xxltext');
  233. if (levelElement) {
  234. const levelMatch = /\d{1,3}/.exec(levelElement.textContent);
  235. if (levelMatch) {
  236. level = Number.parseInt(levelMatch);
  237. }
  238. }
  239.  
  240. return new UserLevel({ uid: request.params.uid, name, level, timeStamp: new Date().getTime() });
  241. }
  242. });
  243. }
  244.  
  245. /**
  246. * @returns {Promise<UserLevel>}
  247. */
  248. async send() {
  249. const key = `uls_${this.params.uid}`;
  250. let result = cache[this.params.uid] || JSON.parse(await GM.getValue(key, "{}"));
  251. const timeStamp = result?.timeStamp;
  252.  
  253. if (!timeStamp || new Date().getTime() - timeStamp >= maxHoursInCache * 60 * 60 * 1000) {
  254. result = await super.send();
  255.  
  256. cache[this.params.uid] = result;
  257. GM.setValue(key, JSON.stringify(result));
  258. }
  259.  
  260. return result;
  261. }
  262.  
  263. /**
  264. * @param {number} uid
  265. * @returns {Promise<UserLevel>}
  266. */
  267. static async send(uid) {
  268. return await new UserLevelSearch(uid).send();
  269. }
  270. };
  271. })();
  272.  
  273. class User {
  274. /** @param {UserParams} param0 */
  275. constructor({
  276. name, uid = 0, gender = null, age = null,
  277. longitude = null, latitude = null, location = null, distanceKM = null,
  278. isReal = null, hasPremium = null, hasSuper = null, isPerma = null,
  279. isOnline = null, room = null, lastSeen = null, regDate = null,
  280. dateToHumanReadable = (date) => date ?
  281. date.toLocaleString('de-DE', { timeStyle: "medium", dateStyle: "short", timeZone: 'CET' }) : '',
  282. }) {
  283. /** @type {string} */
  284. this.name = String(name);
  285. /** @type {number?} */
  286. this.uid = uid;
  287. /** @type {'male'|'female'|'couple'?} */
  288. this.gender = gender;
  289. /** @type {number?} */
  290. this.age = age;
  291.  
  292. /** @type {number?} */
  293. this.longitude = longitude;
  294. /** @type {number?} */
  295. this.latitude = latitude;
  296. /** @type {string?} */
  297. this.location = location;
  298. /** @type {number?} */
  299. this.distanceKM = distanceKM;
  300.  
  301. /** @type {boolean?} */
  302. this.isReal = isReal;
  303. /** @type {boolean?} */
  304. this.hasPremium = hasPremium;
  305. /** @type {boolean?} */
  306. this.hasSuper = hasSuper;
  307. /** @type {boolean?} */
  308. this.isPerma = isPerma;
  309.  
  310. /** @type {boolean?} */
  311. this.isOnline = isOnline;
  312. /** @type {string?} */
  313. this.room = room;
  314. /** @type {Date?} */
  315. this.lastSeen = lastSeen;
  316. /** @type {Date?} */
  317. this.regDate = regDate;
  318.  
  319. /** @type {string[]} */
  320. this.prints = [];
  321. /** @type {string[]} */
  322. this.ipList = [];
  323. /** @type {number?} */
  324. this.scorePassword = null;
  325. /** @type {number?} */
  326. this.scoreFinal = null;
  327. /** @type {number} */
  328. this.guessLogTS = null;
  329.  
  330. /** @type {(date: Date) => string} */
  331. this.dateToHumanReadable = dateToHumanReadable;
  332.  
  333. /** @type {number?} */
  334. this.level = null;
  335. /** @type {number} */
  336. this.levelTS = null;
  337.  
  338. /** @type {string[]} */
  339. this.galleryData = [];
  340. /** @type {number} */
  341. this.galleryDataTS = null;
  342. }
  343.  
  344. /** @type {string} @readonly */
  345. get lastSeenHumanReadable() {
  346. return this.dateToHumanReadable(this.lastSeen);
  347. }
  348.  
  349. /** @type {string} @readonly */
  350. get regDateHumanReadable() {
  351. return this.dateToHumanReadable(this.regDate);
  352. }
  353.  
  354. get galleryAsImgElements() {
  355. if (!this.galleryData) {
  356. return [];
  357. }
  358.  
  359. return this.galleryData.map(data => Object.assign(document.createElement('img'), {
  360. src: data.dataURI
  361. }));
  362. }
  363.  
  364. async updateGalleryHref() {
  365. const pictureLinks = (await HttpRequestHtml.send({
  366. url: "https://www.camamba.com/profile_view.php",
  367. params: Object.assign(
  368. { m: 'gallery' },
  369. this.uid ? { uid: this.uid } : { user: this.name }
  370. ),
  371.  
  372. pageNr: 0,
  373. pagesMaxCount: 500,
  374.  
  375. resultTransformer: (response) => {
  376. const hrefList = [...response.html.querySelectorAll("img.picborder")].map(img => img.src);
  377. return hrefList.map(href => href.slice(0, 0 - ".s.jpg".length) + ".l.jpg");
  378. },
  379. hasNextPage: (_resp, _httpRequestHtml, lastResult) => {
  380. return lastResult.length >= 15;
  381. },
  382. paramsConfiguratorForPageNr: (params, pageNr) => ({ ...params, page: pageNr }),
  383. })).flat();
  384.  
  385. this.galleryData = pictureLinks.map(href => ({ href }));
  386. this.galleryDataTS = new Date().getTime();
  387. }
  388.  
  389. async updateGalleryData(includeUpdateOfHref = true) {
  390. if (includeUpdateOfHref) {
  391. await this.updateGalleryHref();
  392. }
  393.  
  394. const readGalleryData = this.galleryData.map(({ href }) => (async () => {
  395. const dataURI = await HttpRequestBlob.send({ url: href });
  396. return new GalleryImage({ dataURI, href });
  397. })());
  398.  
  399. this.galleryData = await Promise.all(readGalleryData);
  400. this.galleryDataTS = new Date().getTime();
  401. }
  402.  
  403. async updateLevel() {
  404. const { level, timeStamp, name } = await UserLevelSearch.send(this.uid);
  405. this.level = level;
  406. this.levelTS = timeStamp;
  407. this.name = name;
  408. }
  409.  
  410. async updateGuessLog() {
  411. /** @type {GuessLog} */
  412. const guessLog = await GuessLogSearch.send(this.name);
  413. this.guessLogTS = new Date().getTime();
  414.  
  415. this.ipList = guessLog.ipList;
  416. this.prints = guessLog.prints;
  417. this.scorePassword = guessLog.scorePassword;
  418. this.scoreFinal = guessLog.scoreFinal;
  419. }
  420.  
  421. async addNote(text) {
  422. if (!this.uid) {
  423. return await Promise.reject({
  424. status: 500,
  425. statusText: "missing uid"
  426. });
  427. }
  428.  
  429. return await new Promise((res, rej) => GM_xmlhttpRequest({
  430. url: 'https://www.camamba.com/profile_view.php',
  431. method: 'POST',
  432. data: `uid=${this.uid}&modnote=${encodeURIComponent(text)}&m=admin&nomen=1`,
  433. headers: {
  434. "Content-Type": "application/x-www-form-urlencoded"
  435. },
  436. onload: (xhr) => {
  437. res(xhr.responseText);
  438. },
  439. onerror: (xhr) => rej({
  440. status: xhr.status,
  441. statusText: xhr.statusText
  442. }),
  443. }));
  444. }
  445. }
  446.  
  447. class UserSearch extends HttpRequestHtml {
  448. /** @param {{
  449. * name: string?,
  450. * uid: number?,
  451. * gender: ('any' | 'male' | 'female' |'couple')?,
  452. * isOnline: boolean?, hasReal: boolean?, hasPremium: boolean?, hasSuper: boolean?, hasPicture: boolean?,
  453. * isSortByRegDate: boolean?,
  454. * isSortByDistance: boolean?,
  455. * isShowAll: boolean?,
  456. * pageNr: number?,
  457. * pagesMaxCount: number?,
  458. * keepInCacheTimoutMs: number?
  459. * }} param0 */
  460. constructor({
  461. name = null,
  462. uid = 0,
  463. gender = 'any',
  464. isOnline = null,
  465. hasReal = null,
  466. hasPremium = null,
  467. hasSuper = null,
  468. hasPicture = null,
  469. isSortByRegDate = null,
  470. isSortByDistance = null,
  471. isShowAll = null,
  472. pageNr = 1,
  473. pagesMaxCount = 1,
  474. keepInCacheTimoutMs
  475. } = {}) {
  476. let params = Object.assign(
  477. (name ? {
  478. nick: name
  479. } : {}),
  480. {
  481. gender: gender.toLowerCase(),
  482. },
  483. Object.fromEntries(Object.entries({
  484. online: isOnline,
  485. isreal: hasReal,
  486. isprem: hasPremium,
  487. issuper: hasSuper,
  488. picture: hasPicture,
  489. sortreg: isSortByRegDate,
  490. byDistance: isSortByDistance,
  491. showall: isShowAll,
  492. })
  493. .filter(([_k, v]) => typeof v !== 'undefined' && v !== null)
  494. .map(([k, v]) => ([[k], v ? 1 : 0])))
  495. );
  496.  
  497. params = Object.entries(params).map(([key, value]) => key + '=' + value).join('&');
  498.  
  499. if (params.length) {
  500. params += "&";
  501. }
  502. params += `page=${Math.max(pageNr - 1, 0)}`;
  503.  
  504. super({
  505. url: 'https://www.camamba.com/search.php',
  506. params,
  507. pageNr: Math.max(pageNr, 1),
  508. pagesMaxCount: Math.max(pagesMaxCount, 1),
  509. keepInCacheTimoutMs,
  510.  
  511. resultTransformer: (response) => {
  512. /** @type {Array<User>} */
  513. const users = [];
  514.  
  515. for (const trNode of response.html.querySelectorAll('.searchSuper tr, .searchNormal tr')) {
  516. const innerHTML = trNode.innerHTML;
  517.  
  518. const nameMatch = /<a\s+?href=["']javascript:openProfile\(["'](.+?)["']\)/.exec(innerHTML);
  519.  
  520. if (!nameMatch) {
  521. break;
  522. }
  523.  
  524. const user = new User({
  525. name: nameMatch[1],
  526. isReal: /<img src="\/gfx\/real.png"/.test(innerHTML),
  527. hasPremium: /<a href="\/premium.php">/.test(innerHTML),
  528. hasSuper: /<img src="\/gfx\/super_premium.png"/.test(innerHTML),
  529. isOnline: /Online\snow(\s\in|,\snot in chat)/.test(innerHTML),
  530. });
  531.  
  532. const uidMatch = /<a\s+?href=["']javascript:sendMail\(["'](\d{1,8})["']\)/.exec(innerHTML) || /<img\ssrc="\/userpics\/(\d{1,8})/.exec(innerHTML);
  533. if (uidMatch) {
  534. user.uid = Number.parseInt(uidMatch[1]);
  535. }
  536.  
  537. // Längengrad, Breitengrad, Ortsname
  538. const locationMatch = /<a\s+?href="javascript:openMap\((-?\d{1,3}\.\d{8}),(-?\d{1,3}\.\d{8})\);">(.+?)<\/a>/.exec(innerHTML);
  539. if (locationMatch) {
  540. user.longitude = Number.parseFloat(locationMatch[1]);
  541. user.latitude = Number.parseFloat(locationMatch[2]);
  542. user.location = locationMatch[3];
  543. }
  544.  
  545. // Entfernung in km
  546. const distanceMatch = /(\d{1,5})\skm\sfrom\syou/.exec(innerHTML);
  547. if (distanceMatch) {
  548. user.distanceKM = parseInt(distanceMatch[1]);
  549. }
  550.  
  551. // Geschlecht und Alter
  552. const genderAgeMatch = /(male|female|couple),\s(\d{1,4})(?:<br>){2}Online/.exec(innerHTML);
  553. if (genderAgeMatch) {
  554. user.gender = genderAgeMatch[1];
  555. user.age = genderAgeMatch[2];
  556. }
  557.  
  558. // zuletzt Online
  559. if (user.isOnline) {
  560. user.lastSeen = new Date();
  561. } else {
  562. const lastSeenMatch = /(\d{1,4})\s(minutes|hours|days)\sago/.exec(innerHTML);
  563. if (lastSeenMatch) {
  564. const value = parseInt(lastSeenMatch[1]);
  565.  
  566. const factorToMillis = {
  567. 'minutes': 1000 * 60,
  568. 'hours': 1000 * 60 * 60,
  569. 'days': 1000 * 60 * 60 * 24,
  570. }[lastSeenMatch[2]];
  571.  
  572. user.lastSeen = new Date(Date.now() - value * factorToMillis);
  573. }
  574. }
  575.  
  576. // Raumname
  577. const roomMatch = /(?:ago|now)\sin\s([\w\s]+?|p\d{1,8})<br>/.exec(innerHTML);
  578. if (roomMatch) {
  579. user.room = roomMatch[1];
  580. }
  581.  
  582. // regDate
  583. const regDateMatch = /(\d{2}).(\d{2}).(\d{4})\s(\d{1,2}):(\d{2}):(\d{2})/.exec(innerHTML);
  584. if (regDateMatch) {
  585. const regDateDay = regDateMatch[1];
  586. const regDateMonth = regDateMatch[2];
  587. const regDateYear = regDateMatch[3];
  588. const regDateHour = regDateMatch[4];
  589. const regDateMinute = regDateMatch[5];
  590. const regDateSecond = regDateMatch[6];
  591. user.regDate = new Date(regDateYear, regDateMonth - 1, regDateDay, regDateHour, regDateMinute, regDateSecond);
  592. }
  593.  
  594. users.push(user);
  595. }
  596.  
  597. return users;
  598. },
  599.  
  600. hasNextPage: (_resp, _httpRequestHtml, lastResult) => {
  601. return lastResult.length >= 50;
  602. },
  603.  
  604. paramsConfiguratorForPageNr: (params, pageNr) => {
  605. return params.replace(/page=\d+(?:$)/, `page=${pageNr - 1}`);
  606. },
  607. });
  608. this.uid = uid || null;
  609. }
  610.  
  611. /** @returns {Promise<User[]>} */
  612. async send() {
  613. if (this.uid) {
  614. const user = new User({ uid: this.uid });
  615. await user.updateLevel();
  616.  
  617. if (!user.name || user.level) {
  618. return [];
  619. }
  620. if (this.params.nick) {
  621. const unameURIencoded = encodeURIComponent(user.name.toLowerCase());
  622. const unameFromSearchParam = encodeURIComponent(this.params.nick.toLowerCase()).trim();
  623. if (unameURIencoded.includes(unameFromSearchParam)) {
  624. return [];
  625. }
  626. }
  627.  
  628. this.params.nick = user.name;
  629. const result = (await super.send()).flat().find(u => u.uid == this.uid);
  630. if (!result) {
  631. return [];
  632. }
  633.  
  634. return [Object.assign(user, result)];
  635. }
  636.  
  637. return (await super.send()).flat();
  638. }
  639.  
  640. /**
  641. * @param {{
  642. * name: string,
  643. * uid: number?,
  644. * gender: 'any' | 'male' | 'female' |'couple',
  645. * isOnline: boolean,hasReal: boolean, hasPremium: boolean, hasSuper: boolean, hasPicture: boolean,
  646. * isSortByRegDate: boolean,
  647. * isSortByDistance: boolean,
  648. * isShowAll: boolean,
  649. * pageNr: number,
  650. * pagesMaxCount: number,
  651. * keepInCacheTimoutMs: number
  652. * }} param0
  653. * @returns {Promise<User[]>}
  654. */
  655. static async send(param0) {
  656. return await new UserSearch(param0).send();
  657. }
  658. }