Camamba Users Search Library

fetches Users

目前為 2022-12-10 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/446634/1126999/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.  
  199. const cache = {};
  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 maxDaysInCache = 1;
  234. if (typeof cache[uid] === 'undefined' || new Date().getTime() - cache[uid].timeStamp >= maxDaysInCache * 60 * 60 * 1000) {
  235. cache[uid] = await super.send();
  236. }
  237. return cache[uid];
  238. }
  239.  
  240. /**
  241. * @param {number} uid
  242. * @returns {Promise<UserLevel>}
  243. */
  244. static async send(uid) {
  245. return await new UserLevelSearch(uid).send();
  246. }
  247. };
  248. })();
  249.  
  250. class User {
  251. /** @param {UserParams} param0 */
  252. constructor({
  253. name, uid = 0, gender = null, age = null,
  254. longitude = null, latitude = null, location = null, distanceKM = null,
  255. isReal = null, hasPremium = null, hasSuper = null, isPerma = null,
  256. isOnline = null, room = null, lastSeen = null, regDate = null,
  257. dateToHumanReadable = (date) => date ?
  258. date.toLocaleString('de-DE', { timeStyle: "medium", dateStyle: "short", timeZone: 'CET' }) : '',
  259. }) {
  260. /** @type {string} */
  261. this.name = String(name);
  262. /** @type {number?} */
  263. this.uid = uid;
  264. /** @type {'male'|'female'|'couple'?} */
  265. this.gender = gender;
  266. /** @type {number?} */
  267. this.age = age;
  268.  
  269. /** @type {number?} */
  270. this.longitude = longitude;
  271. /** @type {number?} */
  272. this.latitude = latitude;
  273. /** @type {string?} */
  274. this.location = location;
  275. /** @type {number?} */
  276. this.distanceKM = distanceKM;
  277.  
  278. /** @type {boolean?} */
  279. this.isReal = isReal;
  280. /** @type {boolean?} */
  281. this.hasPremium = hasPremium;
  282. /** @type {boolean?} */
  283. this.hasSuper = hasSuper;
  284. /** @type {boolean?} */
  285. this.isPerma = isPerma;
  286.  
  287. /** @type {boolean?} */
  288. this.isOnline = isOnline;
  289. /** @type {string?} */
  290. this.room = room;
  291. /** @type {Date?} */
  292. this.lastSeen = lastSeen;
  293. /** @type {Date?} */
  294. this.regDate = regDate;
  295.  
  296. /** @type {string[]} */
  297. this.prints = [];
  298. /** @type {string[]} */
  299. this.ipList = [];
  300. /** @type {number?} */
  301. this.scorePassword = null;
  302. /** @type {number?} */
  303. this.scoreFinal = null;
  304. /** @type {number} */
  305. this.guessLogTS = null;
  306.  
  307. /** @type {(date: Date) => string} */
  308. this.dateToHumanReadable = dateToHumanReadable;
  309.  
  310. /** @type {number?} */
  311. this.level = null;
  312. /** @type {number} */
  313. this.levelTS = null;
  314.  
  315. /** @type {string[]} */
  316. this.galleryData = [];
  317. /** @type {number} */
  318. this.galleryDataTS = null;
  319. }
  320.  
  321. /** @type {string} @readonly */
  322. get lastSeenHumanReadable() {
  323. return this.dateToHumanReadable(this.lastSeen);
  324. }
  325.  
  326. /** @type {string} @readonly */
  327. get regDateHumanReadable() {
  328. return this.dateToHumanReadable(this.regDate);
  329. }
  330.  
  331. get galleryAsImgElements() {
  332. if (!this.galleryData) {
  333. return [];
  334. }
  335.  
  336. return this.galleryData.map(data => Object.assign(document.createElement('img'), {
  337. src: data.dataURI
  338. }));
  339. }
  340.  
  341. async updateGalleryHref() {
  342. const pictureLinks = (await HttpRequestHtml.send({
  343. url: "https://www.camamba.com/profile_view.php",
  344. params: Object.assign(
  345. { m: 'gallery' },
  346. this.uid ? { uid: this.uid } : { user: this.name }
  347. ),
  348.  
  349. pageNr: 0,
  350. pagesMaxCount: 500,
  351.  
  352. resultTransformer: (response) => {
  353. const hrefList = [...response.html.querySelectorAll("img.picborder")].map(img => img.src);
  354. return hrefList.map(href => href.slice(0, 0 - ".s.jpg".length) + ".l.jpg");
  355. },
  356. hasNextPage: (_resp, _httpRequestHtml, lastResult) => {
  357. return lastResult.length >= 15;
  358. },
  359. paramsConfiguratorForPageNr: (params, pageNr) => ({ ...params, page: pageNr }),
  360. })).flat();
  361.  
  362. this.galleryData = pictureLinks.map(href => ({ href }));
  363. this.galleryDataTS = new Date().getTime();
  364. }
  365.  
  366. async updateGalleryData(includeUpdateOfHref = true) {
  367. if (includeUpdateOfHref) {
  368. await this.updateGalleryHref();
  369. }
  370.  
  371. const readGalleryData = this.galleryData.map(({ href }) => (async () => {
  372. const dataURI = await HttpRequestBlob.send({ url: href });
  373. return new GalleryImage({ dataURI, href });
  374. })());
  375.  
  376. this.galleryData = await Promise.all(readGalleryData);
  377. this.galleryDataTS = new Date().getTime();
  378. }
  379.  
  380. async updateLevel() {
  381. const { level, timeStamp, name } = await UserLevelSearch.send(this.uid);
  382. this.level = level;
  383. this.levelTS = timeStamp;
  384. this.name = name;
  385. }
  386.  
  387. async updateGuessLog() {
  388. /** @type {GuessLog} */
  389. const guessLog = await GuessLogSearch.send(this.name);
  390. this.guessLogTS = new Date().getTime();
  391.  
  392. this.ipList = guessLog.ipList;
  393. this.prints = guessLog.prints;
  394. this.scorePassword = guessLog.scorePassword;
  395. this.scoreFinal = guessLog.scoreFinal;
  396. }
  397.  
  398. async addNote(text) {
  399. return new Promise((res, rej) => {
  400. if (this.uid) {
  401. GM_xmlhttpRequest({
  402. url: 'https://www.camamba.com/profile_view.php',
  403. method: 'POST',
  404. data: `uid=${this.uid}&modnote=${encodeURIComponent(text)}&m=admin&nomen=1`,
  405. headers: {
  406. "Content-Type": "application/x-www-form-urlencoded"
  407. },
  408. onload: (xhr) => {
  409. res(xhr.responseText);
  410. },
  411. onerror: (xhr) => rej({
  412. status: xhr.status,
  413. statusText: xhr.statusText
  414. }),
  415. });
  416. } else {
  417. rej({
  418. status: 500,
  419. statusText: "missing uid"
  420. });
  421. }
  422. });
  423. }
  424. }
  425.  
  426. class UserSearch extends HttpRequestHtml {
  427. /** @param {{
  428. * name: string?,
  429. * uid: number?,
  430. * gender: ('any' | 'male' | 'female' |'couple')?,
  431. * isOnline: boolean?, hasReal: boolean?, hasPremium: boolean?, hasSuper: boolean?, hasPicture: boolean?,
  432. * isSortByRegDate: boolean?,
  433. * isSortByDistance: boolean?,
  434. * isShowAll: boolean?,
  435. * pageNr: number?,
  436. * pagesMaxCount: number?,
  437. * keepInCacheTimoutMs: number?
  438. * }} param0 */
  439. constructor({
  440. name = null,
  441. uid = 0,
  442. gender = 'any',
  443. isOnline = null,
  444. hasReal = null,
  445. hasPremium = null,
  446. hasSuper = null,
  447. hasPicture = null,
  448. isSortByRegDate = null,
  449. isSortByDistance = null,
  450. isShowAll = null,
  451. pageNr = 1,
  452. pagesMaxCount = 1,
  453. keepInCacheTimoutMs
  454. } = {}) {
  455. let params = Object.assign(
  456. (name ? {
  457. nick: name
  458. } : {}),
  459. {
  460. gender: gender.toLowerCase(),
  461. },
  462. Object.fromEntries(Object.entries({
  463. online: isOnline,
  464. isreal: hasReal,
  465. isprem: hasPremium,
  466. issuper: hasSuper,
  467. picture: hasPicture,
  468. sortreg: isSortByRegDate,
  469. byDistance: isSortByDistance,
  470. showall: isShowAll,
  471. })
  472. .filter(([_k, v]) => typeof v !== 'undefined' && v !== null)
  473. .map(([k, v]) => ([[k], v ? 1 : 0])))
  474. );
  475.  
  476. params = Object.entries(params).map(([key, value]) => key + '=' + value).join('&');
  477.  
  478. if (params.length) {
  479. params += "&";
  480. }
  481. params += `page=${Math.max(pageNr - 1, 0)}`;
  482.  
  483. super({
  484. url: 'https://www.camamba.com/search.php',
  485. params,
  486. pageNr: Math.max(pageNr, 1),
  487. pagesMaxCount: Math.max(pagesMaxCount, 1),
  488. keepInCacheTimoutMs,
  489.  
  490. resultTransformer: (response) => {
  491. /** @type {Array<User>} */
  492. const users = [];
  493.  
  494. for (const tdNode of response.html.querySelectorAll('.searchSuper td:nth-child(2), .searchNormal td:nth-child(2)')) {
  495. const innerHTML = tdNode.innerHTML;
  496. const uidMatch = /<a\s+?href=["']javascript:sendMail\(["'](\d{1,8})["']\)/.exec(innerHTML);
  497. const nameMatch = /<a\s+?href=["']javascript:openProfile\(["'](.+?)["']\)/.exec(innerHTML);
  498. if (!uidMatch || !nameMatch) {
  499. break;
  500. }
  501.  
  502. const user = new User({
  503. name: nameMatch[1],
  504. uid: Number.parseInt(uidMatch[1]),
  505. isReal: /<img src="\/gfx\/real.png"/.test(innerHTML),
  506. hasPremium: /<a href="\/premium.php">/.test(innerHTML),
  507. hasSuper: /<img src="\/gfx\/super_premium.png"/.test(innerHTML),
  508. isOnline: /Online\snow(\s\in|,\snot in chat)/.test(innerHTML),
  509. });
  510.  
  511. // Längengrad, Breitengrad, Ortsname
  512. const locationMatch = /<a\s+?href="javascript:openMap\((-?\d{1,3}\.\d{8}),(-?\d{1,3}\.\d{8})\);">(.+?)<\/a>/.exec(innerHTML);
  513. if (locationMatch) {
  514. user.longitude = Number.parseFloat(locationMatch[1]);
  515. user.latitude = Number.parseFloat(locationMatch[2]);
  516. user.location = locationMatch[3];
  517. }
  518.  
  519. // Entfernung in km
  520. const distanceMatch = /(\d{1,5})\skm\sfrom\syou/.exec(innerHTML);
  521. if (distanceMatch) {
  522. user.distanceKM = parseInt(distanceMatch[1]);
  523. }
  524.  
  525. // Geschlecht und Alter
  526. const genderAgeMatch = /(male|female|couple),\s(\d{1,4})(?:<br>){2}Online/.exec(innerHTML);
  527. if (genderAgeMatch) {
  528. user.gender = genderAgeMatch[1];
  529. user.age = genderAgeMatch[2];
  530. }
  531.  
  532. // zuletzt Online
  533. if (user.isOnline) {
  534. user.lastSeen = new Date();
  535. } else {
  536. const lastSeenMatch = /(\d{1,4})\s(minutes|hours|days)\sago/.exec(innerHTML);
  537. if (lastSeenMatch) {
  538. const value = parseInt(lastSeenMatch[1]);
  539.  
  540. const factorToMillis = {
  541. 'minutes': 1000 * 60,
  542. 'hours': 1000 * 60 * 60,
  543. 'days': 1000 * 60 * 60 * 24,
  544. }[lastSeenMatch[2]];
  545.  
  546. user.lastSeen = new Date(Date.now() - value * factorToMillis);
  547. }
  548. }
  549.  
  550. // Raumname
  551. const roomMatch = /(?:ago|now)\sin\s([\w\s]+?|p\d{1,8})<br>/.exec(innerHTML);
  552. if (roomMatch) {
  553. user.room = roomMatch[1];
  554. }
  555.  
  556. // regDate
  557. const regDateMatch = /(\d{2}).(\d{2}).(\d{4})\s(\d{1,2}):(\d{2}):(\d{2})/.exec(innerHTML);
  558. if (regDateMatch) {
  559. const regDateDay = regDateMatch[1];
  560. const regDateMonth = regDateMatch[2];
  561. const regDateYear = regDateMatch[3];
  562. const regDateHour = regDateMatch[4];
  563. const regDateMinute = regDateMatch[5];
  564. const regDateSecond = regDateMatch[6];
  565. user.regDate = new Date(regDateYear, regDateMonth - 1, regDateDay, regDateHour, regDateMinute, regDateSecond);
  566. }
  567.  
  568. users.push(user);
  569. }
  570.  
  571. return users;
  572. },
  573.  
  574. hasNextPage: (_resp, _httpRequestHtml, lastResult) => {
  575. return lastResult.length >= 50;
  576. },
  577.  
  578. paramsConfiguratorForPageNr: (params, pageNr) => {
  579. return params.replace(/page=\d+(?:$)/, `page=${pageNr - 1}`);
  580. },
  581. });
  582. this.uid = uid || null;
  583. }
  584.  
  585. /** @returns {Promise<User[]>} */
  586. async send() {
  587. if (this.uid) {
  588. const user = new User({ uid: this.uid });
  589. await user.updateLevel();
  590.  
  591. if (!user.name || user.level) {
  592. return [];
  593. }
  594. if (this.params.nick) {
  595. const unameURIencoded = encodeURIComponent(user.name.toLowerCase());
  596. const unameFromSearchParam = encodeURIComponent(this.params.nick.toLowerCase()).trim();
  597. if (unameURIencoded.includes(unameFromSearchParam)) {
  598. return [];
  599. }
  600. }
  601.  
  602. this.params.nick = user.name;
  603. const result = (await super.send()).flat().find(u => u.uid == this.uid);
  604. if (!result) {
  605. return [];
  606. }
  607.  
  608. return [Object.assign(user, result)];
  609. }
  610.  
  611. return (await super.send()).flat();
  612. }
  613.  
  614. /**
  615. * @param {{
  616. * name: string,
  617. * uid: number?,
  618. * gender: 'any' | 'male' | 'female' |'couple',
  619. * isOnline: boolean,hasReal: boolean, hasPremium: boolean, hasSuper: boolean, hasPicture: boolean,
  620. * isSortByRegDate: boolean,
  621. * isSortByDistance: boolean,
  622. * isShowAll: boolean,
  623. * pageNr: number,
  624. * pagesMaxCount: number,
  625. * keepInCacheTimoutMs: number
  626. * }} param0
  627. * @returns {Promise<User[]>}
  628. */
  629. static async send(param0) {
  630. return await new UserSearch(param0).send();
  631. }
  632. }