Camamba Users Search Library

fetches Users

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

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

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