Camamba Users Search Library

fetches Users

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

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