Best Python code snippet using locust
handler.js
Source:handler.js
1const simple = require('./lib/simple')2const util = require('util')3const isNumber = x => typeof x === 'number' && !isNaN(x)4const delay = ms => isNumber(ms) && new Promise(resolve => setTimeout(resolve, ms))5module.exports = {6 async handler(chatUpdate) {7 if (global.db.data == null) await loadDatabase()8 this.msgqueque = this.msgqueque || []9 // console.log(chatUpdate)10 if (!chatUpdate) return11 // if (chatUpdate.messages.length > 2 || !chatUpdate.messages.length) return12 if (chatUpdate.messages.length > 1) console.log(chatUpdate.messages)13 let m = chatUpdate.messages[chatUpdate.messages.length - 1]14 if (!m) return15 console.log(JSON.stringify(m, null, 4))16 try {17 m = simple.smsg(this, m) || m18 if (!m) return19 // console.log(m)20 m.exp = 021 m.limit = false22 try {23 let user = global.db.data.users[m.sender]24 if (typeof user !== 'object') global.db.data.users[m.sender] = {}25 if (user) {26 if (!isNumber(user.healt)) user.healt = 10027 if (!isNumber(user.title)) user.title = 028 if (!isNumber(user.stamina)) user.stamina = 10029 if (!isNumber(user.haus)) user.haus = 10030 if (!isNumber(user.laper)) user.laper = 10031 if (!isNumber(user.level)) user.level = 032 if (!('pasangan' in user)) user.pasangan = ''33 if (!isNumber(user.exp)) user.exp = 034 if (!isNumber(user.pc)) user.pc = 035 if (!isNumber(user.korbanngocok)) user.korbanngocok = 036 if (!isNumber(user.ojekk)) user.ojekk = 037 if (!isNumber(user.trofi)) user.trofi= 038 if (!user.rtrofi) user.rtrofi = 'Perunggu'39 if (!isNumber(user.troopcamp)) user.troopcamp = 040 if (!isNumber(user.coin)) user.coin = 041 if (!isNumber(user.atm)) user.atm = 042 if (!isNumber(user.limit)) user.limit = 2043 if (!isNumber(user.glimit)) user.glimit = 2044 if (!isNumber(user.tprem)) user.tprem = 045 if (!isNumber(user.tigame)) user.tigame = 5046 if (!isNumber(user.lastclaim)) user.lastclaim = 047 if (!isNumber(user.money)) user.money = 048 if (!isNumber(user.rumahsakit)) user.rumahsakit= 049 if (!isNumber(user.fortress)) user.fortress = 050 if (!isNumber(user.shield)) user.shield = false51 if (!isNumber(user.pertanian)) user.pertanian = 052 if (!isNumber(user.pertambangan)) user.pertambangan = 053 54 55 if (!isNumber(user.botol)) user.botol = 056 if (!isNumber(user.kardus)) user.kardus = 057 if (!isNumber(user.kaleng)) user.kaleng = 058 if (!isNumber(user.aqua)) user.aqua = 059 if (!isNumber(user.diamond)) user.diamond = 060 if (!isNumber(user.iron)) user.iron = 061 if (!isNumber(user.emas)) user.emas = 062 if (!isNumber(user.arlok)) user.arlok = 063 64 if (!isNumber(user.common)) user.common = 065 if (!isNumber(user.as)) user.as = 066 if (!isNumber(user.uncommon)) user.uncommon = 067 if (!isNumber(user.mythic)) user.mythic = 068 if (!isNumber(user.legendary)) user.legendary = 069 if (!isNumber(user.glory)) user.glory = 070 if (!isNumber(user.enchant)) user.enchant = 071 if (!isNumber(user.pet)) user.pet = 072 if (!isNumber(user.psepick)) user.psepick = 073 if (!isNumber(user.psenjata)) user.psenjata = 074 75 if (!isNumber(user.potion)) user.potion = 076 if (!isNumber(user.sampah)) user.sampah = 077 if (!isNumber(user.armor)) user.armor = 078 if (!isNumber(user.pancing)) user.pancing = 079 //penambah stamina80 if (!isNumber(user.apel)) user.apel = 081 if (!isNumber(user.ayamb)) user.ayamb = 082 if (!isNumber(user.ayamg)) user.ayamg = 083 if (!isNumber(user.sapir)) user.sapir = 084 if (!isNumber(user.ssapi)) user.ssapi = 085 if (!isNumber(user.esteh)) user.esteh = 086 if (!isNumber(user.leleg)) user.leleg = 087 if (!isNumber(user.leleb)) user.leleb = 088 //tools89 if (!isNumber(user.sword)) user.sword = 090 if (!isNumber(user.sworddurability)) user.sworddurability = 091 if (!isNumber(user.pickaxe)) user.pickaxe = 092 if (!isNumber(user.pickaxedurability)) user.pickaxedurability = 093 if (!isNumber(user.fishingrod)) user.fishingrod = 094 if (!isNumber(user.fishingroddurability)) user.fishingroddurability = 095 if (!isNumber(user.umpan)) user.umpan = 096 97 if (!isNumber(user.kucing)) user.kucing = 098 if (!isNumber(user.kucinglastclaim)) user.kucinglastclaim = 099 if (!isNumber(user.kuda)) user.kuda = 0100 if (!isNumber(user.kudalastclaim)) user.kudalastclaim = 0101 if (!isNumber(user.rubah)) user.rubah = 0102 if (!isNumber(user.rubahlastclaim)) user.rubahlastclaim = 0103 if (!isNumber(user.anjing)) user.anjing = 0104 if (!isNumber(user.anjinglastclaim)) user.anjinglastclaim = 0105 if (!isNumber(user.serigalalastclaim)) user.serigalalastclaim = 0106 if (!isNumber(user.nagalastclaim)) user.nagalastclaim = 0107 if (!isNumber(user.phonixlastclaim)) user.phonixlastclaim = 0108 if (!isNumber(user.griffinlastclaim)) user.griffinlastclaim = 0109 if (!isNumber(user.centaurlastclaim)) user.centaurlastclaim = 0110 111 if (!isNumber(user.makananpet)) user.makananpet112 if (!isNumber(user.makanannaga)) user.makanannaga = 0113 if (!isNumber(user.makananphonix)) user.makananphonix = 0114 if (!isNumber(user.makanangriffin)) user.makanangriffin = 0115 if (!isNumber(user.makananserigala)) user.makananserigala = 0116 if (!isNumber(user.makanancentaur)) user.makanancentaur = 0117 118 if (!'Banneduser' in user) user.Banneduser = false119 if (!'BannedReason' in user) user.BannedReason = ''120 if (!isNumber(user.warn)) user.warn = 0121 122 if (!isNumber(user.afk)) user.afk = -1123 if (!'afkReason' in user) user.afkReason = ''124 125 //PET126 if (!isNumber(user.healthmonster)) user.healthmonster = 0127 if (!isNumber(user.anakkucing)) user.anakkucing = 0128 if (!isNumber(user.anakkuda)) user.anakkuda = 0129 if (!isNumber(user.anakrubah)) user.anakrubah = 0130 if (!isNumber(user.anakanjing)) user.anakanjing = 0131 if (!isNumber(user.serigala)) user.serigala = 0132 if (!isNumber(user.anakserigala)) user.anakserigala = 0133 if (!isNumber(user.naga)) user.naga = 0134 if (!isNumber(user.anaknaga)) user.anaknaga = 0135 if (!isNumber(user.phonix)) user.phonix = 0136 if (!isNumber(user.anakphonix)) user.anakphonix = 0137 if (!isNumber(user.griffin)) user.griffin = 0138 if (!isNumber(user.anakgriffin)) user.anakgriffin = 0139 if (!isNumber(user.kyubi)) user.kyubi = 0140 if (!isNumber(user.anakkyubi)) user.anakkyubi = 0141 if (!isNumber(user.centaur)) user.centaur = 0142 if (!isNumber(user.anakcentaur)) user.anakcentaur = 0143 if (!isNumber(user.makananpet)) user.makananpet = 0144 145 if (!isNumber(user.antispam)) user.antispam = 0146 if (!isNumber(user.antispamlastclaim)) user.antispamlastclaim = 0147 148 if (!isNumber(user.kayu)) user.kayu = 0149 if (!('kingdom' in user)) user.kingdom = false150 if (!isNumber(user.batu)) user.batu = 0151 if (!isNumber(user.ramuan)) user.ramuan = 0152 if (!isNumber(user.string)) user.string = 0153 if (!isNumber(user.sword)) user.sword = 0154 if (!isNumber(user.sworddurability)) user.sworddurability = 0155 if (!isNumber(user.pickaxe)) user.pickaxe = 0156 if (!isNumber(user.pickaxedurability)) user.pickaxedurability = 0157 if (!isNumber(user.fishingrod)) user.fishingrod = 0158 if (!isNumber(user.fishingroddurability)) user.fishingroddurability = 0159 160 //mancing161 if (!isNumber(user.paus)) user.paus = 0162 if (!isNumber(user.kepiting)) user.kepiting = 0163 if (!isNumber(user.gurita)) user.gurita = 0164 if (!isNumber(user.cumi)) user.cumi= 0165 if (!isNumber(user.buntal)) user.buntal = 0166 if (!isNumber(user.dory)) user.dory = 0167 if (!isNumber(user.lumba)) user.lumba = 0168 if (!isNumber(user.lobster)) user.lobster = 0169 if (!isNumber(user.hiu)) user.hiu = 0170 if (!isNumber(user.udang)) user.udang = 0171 if (!isNumber(user.ikan)) user.ikan = 0172 if (!isNumber(user.nila)) user.nila = 0173 if (!isNumber(user.bawal)) user.bawal = 0174 if (!isNumber(user.lele)) user.lele = 0175 if (!isNumber(user.orca)) user.orca = 0176 177 if (!isNumber(user.banteng)) user.banteng = 0178 if (!isNumber(user.harimau)) user.harimau = 0179 if (!isNumber(user.gajah)) user.gajah = 0180 if (!isNumber(user.kambing)) user.kambing = 0181 if (!isNumber(user.panda)) user.panda = 0182 if (!isNumber(user.buaya)) user.buaya = 0183 if (!isNumber(user.kerbau)) user.kerbau = 0184 if (!isNumber(user.sapi)) user.sapi = 0185 if (!isNumber(user.monyet)) user.monyet = 0186 if (!isNumber(user.babihutan)) user.babihutan = 0187 if (!isNumber(user.babi)) user.babi = 0188 if (!isNumber(user.ayam)) user.ayam = 0189 190 if (!isNumber(user.lastadventure)) user.lastadventure = 0191 if (!isNumber(user.lastkill)) user.lastkill = 0192 if (!isNumber(user.lastfishing)) user.lastfishing = 0193 if (!isNumber(user.lastdungeon)) user.lastdungeon = 0194 if (!isNumber(user.lastwar)) user.lastwar = 0195 if (!isNumber(user.lastsda)) user.lastsda = 0196 if (!isNumber(user.lastberbru)) user.lastberbru = 0197 if (!isNumber(user.lastduel)) user.lastduel = 0198 if (!isNumber(user.lastjb)) user.lastjb = 0199 if (!isNumber(user.lastSetStatus)) user.lastSetStatus = 0200 if (!isNumber(user.lastmining)) user.lastmining = 0201 if (!isNumber(user.lasthunt)) user.lasthunt = 0202 if (!isNumber(user.lastngocok)) user.lastngocok = 0203 if (!isNumber(user.lastgift)) user.lastgift = 0204 if (!isNumber(user.lastrob)) user.lastrob = 0205 if (!isNumber(user.lastngojek)) user.lastngojek = 0206 if (!isNumber(user.lastgrab)) user.lastgrab = 0207 if (!isNumber(user.lastberkebon)) user.lastberkebon = 0208 if (!isNumber(user.lastcodereg)) user.lastcodereg = 0209 if (!isNumber(user.lastdagang)) user.lastdagang = 0210 if (!isNumber(user.lasthourly)) user.lasthourly = 0211 if (!isNumber(user.lastweekly)) user.lastweekly = 0212 if (!isNumber(user.lastmonthly)) user.lastmonthly = 0213 if (!isNumber(user.lastIstigfar)) user.lastIstigfar = 0214 if (!isNumber(user.lastturu)) user.lastturu = 0215 if (!isNumber(user.lastseen)) user.lastseen = 0216 if (!isNumber(user.lastbansos)) user.lastbansos = 0217 if (!isNumber(user.lastrampok)) user.lastrampok = 0218 if (!('registered' in user)) user.registered = false219 if (!user.registered) {220 if (!('name' in user)) user.name = this.getName(m.sender)221 222 if (!isNumber(user.apel)) user.apel = 0223 if (!isNumber(user.anggur)) user.anggur = 0224 if (!isNumber(user.jeruk)) user.jeruk = 0225 if (!isNumber(user.semangka)) user.semangka = 0226 if (!isNumber(user.mangga)) user.mangga = 0227 if (!isNumber(user.stroberi)) user.stroberi = 0228 if (!isNumber(user.pisang)) user.pisang = 0229 if (!isNumber(user.kayu)) user.kayu = 0230 if (!isNumber(user.emas)) user.emas = 0231 if (!isNumber(user.makanan)) user.makanan = 0232 if (!isNumber(user.bibitanggur)) user.bibitanggur = 0233 if (!isNumber(user.bibitpisang)) user.bibitpisang = 0234 if (!isNumber(user.bibitapel)) user.bibitapel = 0235 if (!isNumber(user.bibitmangga)) user.bibitmangga = 0236 if (!isNumber(user.bibitjeruk)) user.bibitjeruk = 0237 238 239 if (!isNumber(user.age)) user.age = -1240 if (!isNumber(user.premiumDate)) user.premiumDate = -1241 if (!isNumber(user.regTime)) user.regTime = -1242 243 }244 if (!isNumber(user.level)) user.level = 0245 if (!user.job) user.job = 'Pengangguran'246 if (!user.lbars) user.lbars = '[âââââââââ]'247 if (!user.premium) user.premium = false248 if (!user.premium) user.premiumTime= 0249 if (!user.role) user.role = 'Newbie ã¡'250 if (!('autolevelup' in user)) user.autolevelup = true251 if (!('lastIstigfar' in user)) user.lastIstigfar = true252 } else global.db.data.users[m.sender] = {253 healt: 100,254 title: '',255 haus: 100,256 laper: 100,257 tprem: 0,258 stamina : 100,259 level: 0,260 pasangan: '',261 pc : 0,262 exp: 0,263 coin: 0,264 atm: 0,265 limit: 20,266 tigame: 50,267 lastclaim: 0,268 money: 0,269 diamond: 0,270 iron: 0,271 emas: 0,272 common: 0,273 uncommon: 0,274 mythic: 0,275 legendary: 0,276 rumahsakit: 0,277 fortress: 0,278 trofi: 0,279 rtrofi: 'perunggu',280 makanan: 0,281 troopcamp: 0,282 shield: 0,283 arlok: 0,284 ojekk: 0,285 korbanngocok: 0,286 //mancing287 as: 0,288 paus: 0,289 kepiting: 0,290 gurita: 0,291 cumi: 0,292 buntal: 0,293 dory: 0,294 lumba: 0,295 lobster: 0,296 hiu: 0,297 lele: 0,298 nila: 0,299 bawal: 0,300 udang: 0,301 ikan: 0,302 orca: 0,303 banteng: 0,304 harimau: 0,305 gajah: 0,306 kambing: 0,307 panda: 0,308 buaya: 0,309 kerbau : 0,310 sapi: 0,311 monyet : 0,312 babihutan: 0,313 babi: 0,314 ayam: 0,315 apel: 20,316 ayamb: 0,317 ayamg: 0,318 ssapi: 0,319 sapir: 0,320 leleb: 0,321 leleg: 0,322 esteh: 0,323 pet: 0,324 potion: 0,325 sampah: 0,326 armor: 0,327 kucing: 0,328 kucinglastclaim: 0,329 kuda: 0,330 kudalastclaim: 0,331 rubah: 0,332 rubahlastclaim: 0,333 anjing: 0,334 anjinglastclaim: 0,335 naga: 0,336 nagalastclaim: 0,337 griffin: 0,338 griffinlastclaim: 0,339 centaur: 0,340 centaurlastclaim: 0,341 serigala: 0,342 serigalalastclaim: 0,343 phonix: 0,344 phonixlastclaim: 0,345 makanannaga: 0,346 makananphonix: 0,347 makanancentaur: 0,348 makananserigala: 0,349 350 Banneduser: false,351 BannedReason: '',352 warn: 0,353 afk: -1,354 afkReason: '',355 anakkucing: 0,356 anakkuda: 0,357 anakrubah: 0,358 anakanjing: 0,359 makananpet: 0,360 antispam: 0,361 antispamlastclaim: 0,362 kayu: 0,363 batu: 0,364 string: 0,365 umpan: 0,366 sword: 0,367 sworddurability: 0,368 pickaxe: 0,369 pickaxedurability: 0,370 fishingrod: 0,371 fishingroddurability: 0,372 lastadventure: 0,373 lastkill: 0,374 lastfishing: 0,375 lastdungeon: 0,376 lastduel: 0,377 lastmining: 0,378 lasthourly: 0,379 lasthunt: 0,380 lastweekly: 0,381 lastmonthly: 0,382 lastjb: 0,383 lastrob: 0,384 lastdaang: 0,385 lastngojek: 0,386 lastgrab: 0,387 lastngocok: 0,388 lastturu: 0,389 lastseen: 0,390 lastSetStatus: 0,391 registered: false,392 apel: 20,393 mangga: 0,394 stroberi: 0,395 semangka: 0,396 jeruk: 0,397 semangka: 0,398 name: this.getName(m.sender),399 age: -1,400 regTime: -1,401 premium: false, 402 premiumTime: 0,403 job: 'Pengangguran', 404 lbars: '[âââââââââ]', 405 role: 'Newbie ã¡', 406 registered: false,407 name: this.getName(m.sender),408 age: -1,409 regTime: -1,410 autolevelup: true,411 lastIstigfar: 0,412 }413 let chat = global.db.data.chats[m.chat]414 if (typeof chat !== 'object') global.db.data.chats[m.chat] = {}415 if (chat) {416 if (!('isBanned' in chat)) chat.isBanned = false417 if (!('welcome' in chat)) chat.welcome = true418 if (!('detect' in chat)) chat.detect = false419 if (!('sWelcome' in chat)) chat.sWelcome = ''420 if (!('sBye' in chat)) chat.sBye = ''421 if (!('sPromote' in chat)) chat.sPromote = ''422 if (!('sDemote' in chat)) chat.sDemote = ''423 if (!('delete' in chat)) chat.delete = true424 if (!('antiLink' in chat)) chat.antiLink = true425 if (!('viewonce' in chat)) chat.viewonce = false426 if (!('antiToxic' in chat)) chat.antiToxic = false427 } else global.db.data.chats[m.chat] = {428 isBanned: false,429 welcome: true,430 detect: false,431 sWelcome: '',432 sBye: '',433 sPromote: '',434 sDemote: '',435 delete: true,436 antiLink: false,437 viewonce: false,438 antiToxic: true,439 }440 } catch (e) {441 console.error(e)442 }443 if (opts['nyimak']) return444 if (!m.fromMe && opts['self']) return445 if (opts['pconly'] && m.chat.endsWith('g.us')) return446 if (opts['gconly'] && !m.chat.endsWith('g.us')) return447 if (opts['swonly'] && m.chat !== 'status@broadcast') return448 if (typeof m.text !== 'string') m.text = ''449 if (opts['queque'] && m.text) {450 this.msgqueque.push(m.id || m.key.id)451 await delay(this.msgqueque.length * 1000)452 }453 for (let name in global.plugins) {454 let plugin = global.plugins[name]455 if (!plugin) continue456 if (plugin.disabled) continue457 if (!plugin.all) continue458 if (typeof plugin.all !== 'function') continue459 try {460 await plugin.all.call(this, m, chatUpdate)461 } catch (e) {462 if (typeof e === 'string') continue463 console.error(e)464 }465 }466 if (m.isBaileys) return467 m.exp += Math.ceil(Math.random() * 10)468 let usedPrefix469 let _user = global.db.data && global.db.data.users && global.db.data.users[m.sender]470 let isROwner = [global.conn.user.jid, ...global.owner].map(v => v.replace(/[^0-9]/g, '') + '@s.whatsapp.net').includes(m.sender)471 let isOwner = isROwner || m.fromMe472 let isMods = isOwner || global.mods.map(v => v.replace(/[^0-9]/g, '') + '@s.whatsapp.net').includes(m.sender)473 let isPrems = isROwner || global.prems.map(v => v.replace(/[^0-9]/g, '') + '@s.whatsapp.net').includes(m.sender)474 let groupMetadata = (m.isGroup ? (conn.chats[m.chat] || {}).metadata : {}) || {}475 let participants = (m.isGroup ? groupMetadata.participants : []) || []476 let user = (m.isGroup ? participants.find(u => conn.decodeJid(u.id) === m.sender) : {}) || {} // User Data477 let bot = (m.isGroup ? participants.find(u => conn.decodeJid(u.id) == this.user.jid) : {}) || {} // Your Data478 let isAdmin = user && user.admin || false // Is User Admin?479 let isBotAdmin = bot && bot.admin || false // Are you Admin?480 for (let name in global.plugins) {481 let plugin = global.plugins[name]482 if (!plugin) continue483 if (plugin.disabled) continue484 if (!opts['restrict']) if (plugin.tags && plugin.tags.includes('admin')) {485 // global.dfail('restrict', m, this)486 continue487 }488 const str2Regex = str => str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')489 let _prefix = plugin.customPrefix ? plugin.customPrefix : conn.prefix ? conn.prefix : global.prefix490 let match = (_prefix instanceof RegExp ? // RegExp Mode?491 [[_prefix.exec(m.text), _prefix]] :492 Array.isArray(_prefix) ? // Array?493 _prefix.map(p => {494 let re = p instanceof RegExp ? // RegExp in Array?495 p :496 new RegExp(str2Regex(p))497 return [re.exec(m.text), re]498 }) :499 typeof _prefix === 'string' ? // String?500 [[new RegExp(str2Regex(_prefix)).exec(m.text), new RegExp(str2Regex(_prefix))]] :501 [[[], new RegExp]]502 ).find(p => p[1])503 if (typeof plugin.before === 'function') if (await plugin.before.call(this, m, {504 match,505 conn: this,506 participants,507 groupMetadata,508 user,509 bot,510 isROwner,511 isOwner,512 isAdmin,513 isBotAdmin,514 isPrems,515 chatUpdate,516 })) continue517 if (typeof plugin !== 'function') continue518 if ((usedPrefix = (match[0] || '')[0])) {519 let noPrefix = m.text.replace(usedPrefix, '')520 let [command, ...args] = noPrefix.trim().split` `.filter(v => v)521 args = args || []522 let _args = noPrefix.trim().split` `.slice(1)523 let text = _args.join` `524 command = (command || '').toLowerCase()525 let fail = plugin.fail || global.dfail // When failed526 let isAccept = plugin.command instanceof RegExp ? // RegExp Mode?527 plugin.command.test(command) :528 Array.isArray(plugin.command) ? // Array?529 plugin.command.some(cmd => cmd instanceof RegExp ? // RegExp in Array?530 cmd.test(command) :531 cmd === command532 ) :533 typeof plugin.command === 'string' ? // String?534 plugin.command === command :535 false536 if (!isAccept) continue537 m.plugin = name538 if (m.chat in global.db.data.chats || m.sender in global.db.data.users) {539 let chat = global.db.data.chats[m.chat]540 let user = global.db.data.users[m.sender]541 if (name != 'unbanchat.js' && chat && chat.isBanned) return // Except this542 if (name != 'unbanuser.js' && user && user.banned) return543 }544 if (plugin.rowner && plugin.owner && !(isROwner || isOwner)) { // Both Owner545 fail('owner', m, this)546 continue547 }548 if (plugin.rowner && !isROwner) { // Real Owner549 fail('rowner', m, this)550 continue551 }552 if (plugin.owner && !isOwner) { // Number Owner553 fail('owner', m, this)554 continue555 }556 if (plugin.mods && !isMods) { // Moderator557 fail('mods', m, this)558 continue559 }560 if (plugin.premium && !isPrems) { // Premium561 fail('premium', m, this)562 continue563 }564 if (plugin.group && !m.isGroup) { // Group Only565 fail('group', m, this)566 continue567 } else if (plugin.botAdmin && !isBotAdmin) { // You Admin568 fail('botAdmin', m, this)569 continue570 } else if (plugin.admin && !isAdmin) { // User Admin571 fail('admin', m, this)572 continue573 }574 if (plugin.private && m.isGroup) { // Private Chat Only575 fail('private', m, this)576 continue577 }578 if (plugin.register == true && _user.registered == false) { // Butuh daftar?579 fail('unreg', m, this)580 continue581 }582 m.isCommand = true583 let xp = 'exp' in plugin ? parseInt(plugin.exp) : 17 // XP Earning per command584 if (xp > 200) m.reply('Ngecit -_-') // Hehehe585 else m.exp += xp586 if (!isPrems && plugin.limit && global.db.data.users[m.sender].limit < plugin.limit * 1) {587 this.reply(m.chat, `Limit anda habis, silahkan beli melalui *${usedPrefix}buy*`, m)588 continue // Limit habis589 }590 if (plugin.level > _user.level) {591 this.reply(m.chat, `diperlukan level ${plugin.level} untuk menggunakan perintah ini. Level kamu ${_user.level}`, m)592 continue // If the level has not been reached593 }594 let extra = {595 match,596 usedPrefix,597 noPrefix,598 _args,599 args,600 command,601 text,602 conn: this,603 participants,604 groupMetadata,605 user,606 bot,607 isROwner,608 isOwner,609 isAdmin,610 isBotAdmin,611 isPrems,612 chatUpdate,613 }614 try {615 await plugin.call(this, m, extra)616 if (!isPrems) m.limit = m.limit || plugin.limit || false617 } catch (e) {618 // Error occured619 m.error = e620 console.error(e)621 if (e) {622 let text = util.format(e)623 for (let key of Object.values(global.APIKeys))624 text = text.replace(new RegExp(key, 'g'), '#HIDDEN#')625 m.reply(text)626 }627 } finally {628 // m.reply(util.format(_user))629 if (typeof plugin.after === 'function') {630 try {631 await plugin.after.call(this, m, extra)632 } catch (e) {633 console.error(e)634 }635 }636 if (m.limit) m.reply(+ m.limit + ' Limit terpakai')637 }638 break639 }640 }641 } catch (e) {642 console.error(e)643 } finally {644 //console.log(global.db.data.users[m.sender])645 let user, stats = global.db.data.stats646 if (m) {647 if (m.sender && (user = global.db.data.users[m.sender])) {648 user.exp += m.exp649 user.limit -= m.limit * 1650 }651 let stat652 if (m.plugin) {653 let now = + new Date654 if (m.plugin in stats) {655 stat = stats[m.plugin]656 if (!isNumber(stat.total)) stat.total = 1657 if (!isNumber(stat.success)) stat.success = m.error != null ? 0 : 1658 if (!isNumber(stat.last)) stat.last = now659 if (!isNumber(stat.lastSuccess)) stat.lastSuccess = m.error != null ? 0 : now660 } else stat = stats[m.plugin] = {661 total: 1,662 success: m.error != null ? 0 : 1,663 last: now,664 lastSuccess: m.error != null ? 0 : now665 }666 stat.total += 1667 stat.last = now668 if (m.error == null) {669 stat.success += 1670 stat.lastSuccess = now671 }672 }673 }674 // try {675 // require('./lib/print')(m, this)676 // } catch (e) {677 // console.log(m, m.quoted, e)678 // }679 if (opts['autoread']) await this.chatRead(m.chat, m.isGroup ? m.sender : undefined, m.id || m.key.id).catch(() => { })680 let quequeIndex = this.msgqueque.indexOf(m.id || m.key.id)681 if (opts['queque'] && m.text && quequeIndex !== -1) this.msgqueque.splice(quequeIndex, 1)682 }683 },684 async participantsUpdate({ id, participants, action }) {685 if (opts['self']) return686 // if (id in conn.chats) return // First login will spam687 if (global.isInit) return688 let chat = global.db.data.chats[id] || {}689 let fetch = require('node-fetch')690 let text = ''691 switch (action) {692 case 'add':693 case 'remove':694 if (chat.welcome) {695 let groupMetadata = await this.groupMetadata(id) || (conn.chats[id] || {}).metadata696 for (let user of participants) {697 let pp = './src/welcome.jpg'698 try {699 pp = await this.profilePictureUrl(user, 'image')700 } catch (e) {701 } finally {702 text = (action === 'add' ? (chat.sWelcome || this.welcome || conn.welcome || 'Hi, Selamat Datang').replace('@subject', groupMetadata.subject).replace('@desc', groupMetadata.desc.toString()) :703 (chat.sBye || this.bye || conn.bye || 'Selamat tinggal'))704 this.sendButtonImg(id, pp, text, "Group Message", "OKE", "Ok", null)705 }706 }707 }708 break709 case 'promote':710 text = (chat.sPromote || this.spromote || conn.spromote || '@user ```is now Admin```')711 case 'demote':712 if (!text) text = (chat.sDemote || this.sdemote || conn.sdemote || '@user ```is no longer Admin```')713 text = text.replace('@user', '@' + participants[0].split('@')[0])714 if (chat.detect) this.sendMessage(id, text, MessageType.extendedText, {715 contextInfo: {716 mentionedJid: this.parseMention(text)717 }718 })719 break720 }721 },722 async delete({ remoteJid, fromMe, id, participant }) {723 if (fromMe) return724 let chats = Object.entries(conn.chats).find(([user, data]) => data.messages && data.messages[id])725 if (!chats) return726 let msg = JSON.parse(chats[1].messages[id])727 let chat = global.db.data.chats[msg.key.remoteJid] || {}728 if (chat.delete) return729 await this.reply(msg.key.remoteJid, `730Terdeteksi @${participant.split`@`[0]} telah menghapus pesan731Untuk mematikan fitur ini, ketik732*.enable delete*733`.trim(), msg, {734 mentions: [participant]735 })736 this.copyNForward(msg.key.remoteJid, msg).catch(e => console.log(e, msg))737 }738}739global.dfail = (type, m, conn) => {740 let msg = {741 rowner: 'Perintah ini hanya dapat digunakan oleh _*OWWNER!1!1!*_',742 owner: 'Perintah ini hanya dapat digunakan oleh _*Owner Bot*_!',743 mods: 'Perintah ini hanya dapat digunakan oleh _*Moderator*_ !',744 premium: 'Perintah ini hanya untuk member _*Premium*_ !',745 group: 'Perintah ini hanya dapat digunakan di grup!',746 private: 'Perintah ini hanya dapat digunakan di Chat Pribadi!',747 admin: 'Perintah ini hanya untuk *Admin* grup!',748 botAdmin: 'Jadikan bot sebagai *Admin* untuk menggunakan perintah ini!',749 unreg: 'Silahkan daftar untuk menggunakan fitur ini dengan cara mengetik:\n\n*#daftar nama.umur*\n\nContoh: *#daftar Mansur.16*',750 restrict: 'Fitur ini di *disable*!'751 }[type]752 if (msg) return m.reply(msg)753}754let fs = require('fs')755let chalk = require('chalk')756let file = require.resolve(__filename)757fs.watchFile(file, () => {758 fs.unwatchFile(file)759 console.log(chalk.redBright("Update 'handler.js'"))760 delete require.cache[file]761 if (global.reloadHandler) console.log(global.reloadHandler())...
user_api.py
Source:user_api.py
1from flask_restful import Resource2from flask import request, session3from mongoengine import NotUniqueError4import smtplib, ssl5import os6import pdfkit7from email.mime.text import MIMEText8from email.mime.multipart import MIMEMultipart9from email.mime.base import MIMEBase10from email import encoders11from jobmatcher.config import config12from jobmatcher.server.authentication.authentication import require_authentication13from jobmatcher.server.authentication.web_token import generate_access_token14from jobmatcher.server.utils import utils as u15from jobmatcher.server.modules.user.User import User16from jobmatcher.server.modules.cv.CV import CV17from jobmatcher.server.modules.job.job import Job18from jobmatcher.server.utils.nltk.extract_details import extract_location,extract_type19from jobmatcher.server.utils.location.location import one_city20from jobmatcher.server.utils.dict_lang_programing import recommendation21from jobmatcher.server.utils.location.location import matchHandler22from jobmatcher.server.utils.SOS import pdfFIle23from jobmatcher.server.utils.word2vec.matching import match_jobs2cv,get_list_matching_job24from jobmatcher.server.modules.user.user_api_utils import findMatchWord2vec25import operator, datetime26class RegisterUserApi(Resource):27 def post(self):28 payload = request.json.get('body')29 try:30 user = User(31 first_name=payload.get('first_name'),32 last_name=payload.get('last_name'),33 email=payload.get('email').lower(),34 active=True,35 tags=payload.get('tags')36 )37 user.set_password(payload.get('password'))38 user.save()39 except NotUniqueError as e:40 return {'errors': ['Email address already in use']}, u.HTTP_BAD_INPUT41 # user_schema = UserSchema(exclude=['password_hash'])42 # response = user_schema.dump(user).data43 response = {}44 response['success'] = True45 response['token'] = generate_access_token(user).decode('utf-8')46 return response, u.HTTP_CREATED47class SignUserApi(Resource):48 def post(self):49 payload = request.json50 user = User.objects.get(email=payload.get('email', None))51 print("SUCCESS!!!!!!!!!")52 # userEmail = User.objects(email="test@email.com")53 # # print(userEmail)54 for user in User.objects.get(email="test@email.com"):55 print(user.email)56 self.find_by_email("test@email.com")57class UserApi(Resource):58 @require_authentication59 def put(self, user_id):60 """61 edits a user profile62 :return:63 """64 payload = request.json65class UserUploadApi(Resource):66 @require_authentication67 def post(self, user_id):68 try:69 # check that the given user_id matches the logged in user id70 assert user_id == session['user']['id']71 except AssertionError:72 return {'errors': ['You are Unauthorized in this EP']}, u.HTTP_UNAUTHORIZED73 payload = request.json74 # get the user instance from the users collection75 user = User.objects.get(pk=user_id)76 ##############77 if user.cvs != []:78 print('Already exist a cv file, first delete')79 # already have a cv file80 return 'cv' , u.HTTP_CREATED81 ##############82 cv = CV(83 file=payload.get('body')['file_name'],84 text=payload.get('data'),85 user=user.to_dbref()86 )87 cv.save()88 # add the CV DBRef to the user cvs list89 user.cvs.append(cv.to_dbref())90 user.save()91 return {}, u.HTTP_CREATED92 @require_authentication93 def get(self, user_id):94 try:95 # check that the given user_id matches the logged in user id96 assert user_id == session['user']['id']97 except AssertionError:98 return {'errors': ['You are Unauthorized in this EP']}, u.HTTP_UNAUTHORIZED99 user = User.objects.get(pk=user_id)100 cv_length = len(user.cvs)101 if user.cvs == []:102 return 'failed'103 cv_file_name = user.cvs[0].file104 return [cv_length, cv_file_name]105 @require_authentication106 def delete(self, user_id):107 try:108 assert user_id == session['user']['id']109 user = User.objects.get(pk=user_id)110 if user.cvs == []:111 return 'failed'112 user_cvs = user.cvs[0].id113 print("user_cvs: ", user_cvs)114 cv = CV.objects.get(pk=user_cvs)115 print("cv.file: ", cv.file)116 cv.delete()117 user.save()118 # print(' user.cvs == []', User.objects.get(pk=user_id).cvs == [])119 # print('cv not in CV.objects', cv not in CV.objects())120 # delete cheking121 if cv not in CV.objects():122 return 'success'123 else:124 return 'error'125 # if cv.delete():126 # print("cv DELETED!!!")127 # print("$$$ ", user.cvs[0].id)128 #129 # print("$$$ ", user.cvs[0].file)130 # for cv in user.cvs:131 # if cv.id == user_cvs:132 # print('cv ',cv.id)133 # user.cvs.append(cv.to_dbref())134 # user.save()135 except AssertionError:136 return {'errors': ['You are Unauthorized in this EP']}, u.HTTP_UNAUTHORIZED137class UserUpdateApi(Resource):138 def post(self, user_id):139 try:140 # check that the given user_id matches the logged in user id141 assert user_id == session['user']['id']142 except AssertionError:143 return {'errors': ['You are Unauthorized in this EP']}, u.HTTP_UNAUTHORIZED144 print('------ post update profile ------')145 payload = request.json.get('body')146 # print(payload)147 user = User(148 first_name=payload.get('first_name'),149 last_name=payload.get('last_name'),150 email=payload.get('email').lower(),151 active=True,152 tags=payload.get('tags')153 )154 user.set_password(payload.get('password'))155 ppost = User.objects.get(email=payload.get('email', None))156 ppost.first_name=user.first_name157 ppost.last_name = user.last_name158 if(ppost.password_hash!=payload.get('password')):159 ppost.password_hash = user.password_hash160 ppost.active = user.active161 ppost.tags=user.tags162 ppost.save()163 def get (self,user_id):164 # try:165 # # check that the given user_id matches the logged in user id166 # assert user_id == session['user']['id']167 # except AssertionError:168 # return {'errors': ['You are Unauthorized in this EP']}, u.HTTP_UNAUTHORIZED169 print('------ get update profile ------')170 # print(user_id)171 user=User.objects.get(id=user_id)172 # print (user.first_name)173 # print("user_tags_amount")174 # print(len(user.tags))175 return [user.first_name,user.last_name,user.email,len(user.tags),user.tags,user.password_hash]176class UserSetStusApi(Resource):177 @require_authentication178 def get (self,user_id):179 try:180 # check that the given user_id matches the logged in user id181 assert user_id == session['user']['id']182 except AssertionError:183 return {'errors': ['You are Unauthorized in this EP']}, u.HTTP_UNAUTHORIZED184 print('------ get state status ------')185 # print(user_id)186 user=User.objects.get(id=user_id)187 # user.find=False188 # user.save()189 # print (user.first_name)190 return [user.find]191 @require_authentication192 def post (self,user_id):193 try:194 # check that the given user_id matches the logged in user id195 assert user_id == session['user']['id']196 except AssertionError:197 return {'errors': ['You are Unauthorized in this EP']}, u.HTTP_UNAUTHORIZED198 print('------ post state status ------')199 payload = request.json.get('body')200 find =payload.get('find')201 user=User.objects.get(id=user_id)202 user.find=find203 user.save()204 # print (user.first_name)205 return [user.find]206class UserPreferencesApi(Resource):207 @require_authentication208 def post(self, user_id):209 try:210 # check that the given user_id matches the logged in user id211 assert user_id == session['user']['id']212 except AssertionError:213 return {'errors': ['You are Unauthorized in this EP']}, u.HTTP_UNAUTHORIZED214 print("UserPreferencesApi")215 print(user_id)216 payload = request.json.get('body')217 kind = payload.get('type')218 print(kind)219 user = User.objects.get(pk=user_id)220 print("#### " + user.email)221 user.job_type = kind222 print(user.job_type)223 user.save()224 @require_authentication225 def get(self,user_id):226 try:227 # check that the given user_id matches the logged in user id228 assert user_id == session['user']['id']229 except AssertionError:230 return {'errors': ['You are Unauthorized in this EP']}, u.HTTP_UNAUTHORIZED231 user = User.objects.get(pk=user_id)232 return [user.job_type]233class UserFindMatchApi(Resource):234 @require_authentication235 def post(self, user_id):236 try:237 # check that the given user_id matches the logged in user id238 assert user_id == session['user']['id']239 except AssertionError:240 return {'errors': ['You are Unauthorized in this EP']}, u.HTTP_UNAUTHORIZED241 # print(" === UserFindMatchApi ===")242 # print("user_id: " + user_id)243 user = User.objects.get(pk=user_id)244 resume = user.cvs[0].text245 user_location = []246 user_location = extract_location(resume)247 job = Job.objects.first() # getting job id for the first object - temp for now248 job_id = job.id249 matchHandler(job_id, user_location)250class UserFindMatchWord2vecApi(Resource):251 @require_authentication252 def post(self, user_id):253 try:254 # check that the given user_id matches the logged in user id255 assert user_id == session['user']['id']256 except AssertionError:257 return {'errors': ['You are Unauthorized in this EP']}, u.HTTP_UNAUTHORIZED258 print('~~~~~ UserFindMatchWord2vecApi ~~~~~')259 user = User.objects.get(pk=user_id)260 if len(user.cvs) == 0:261 # print('len(user.cvs)')262 return None263 cv_id = user.cvs[0].id264 cv_text = user.cvs[0].text265 #for location score266 user_location = []267 user_location = extract_location(cv_text)268 jobs_id_list = match_jobs2cv(cv_text,user_location)269 for k,v in jobs_id_list.items():270 if k not in user.jobs:271 user.favorite[k]=False272 user.sending[k]=False273 user.replay[k]=False274 user.jobs[k] = v275 user.save()276 response = get_list_matching_job(jobs_id_list,user_id)277 # print(response)278 return response279 # response={}280 # jobs = user.jobs281 #282 # for k ,v in jobs.items():283 # job = Job.objects.get(identifier=k)284 # response[k]=(job.role_name,job.link,v,extract_type(job.type),285 # user.favorite[k],user.sending[k],user.replay[k])286 # print(response)287 # return response288class UserFindMatchWord2vecApi2(Resource):289 @require_authentication290 def post(self, user_id):291 try:292 # check that the given user_id matches the logged in user id293 assert user_id == session['user']['id']294 except AssertionError:295 return {'errors': ['You are Unauthorized in this EP']}, u.HTTP_UNAUTHORIZED296 print('~~~~~ UserFindMatchWord2vecApi ~~~~~')297 user = User.objects.get(pk=user_id)298 if len(user.cvs) == 0:299 # print('len(user.cvs)')300 return None301 # cv_id = user.cvs[0].id302 # cv_text = user.cvs[0].text303 # #for location score304 # user_location = []305 # user_location = extract_location(cv_text)306 # jobs_id_list = match_jobs2cv(cv_text,user_location)307 # for k,v in jobs_id_list.items():308 # if k not in user.jobs:309 # user.favorite[k]=False310 # user.sending[k]=False311 # user.replay[k]=False312 # user.jobs[k] = v313 # user.save()314 # response = get_list_matching_job(jobs_id_list,user_id)315 # print(response)316 # return response317 response={}318 jobs = user.jobs319 for k ,v in jobs.items():320 job = Job.objects.get(identifier=k)321 response[k]=(job.role_name,job.link,v,extract_type(job.type),322 user.favorite[k],user.sending[k],user.replay[k])323 # print(response)324 return response325class UserGetRecommendation(Resource):326 @require_authentication327 def post(self, user_id):328 try:329 # check that the given user_id matches the logged in user id330 assert user_id == session['user']['id']331 except AssertionError:332 return {'errors': ['You are Unauthorized in this EP']}, u.HTTP_UNAUTHORIZED333 print("UserGetRecommendation")334 # rec = []335 rec = recommendation(user_id)336 # print("rec:")337 # print(rec)338 return rec339class jobsSortBYscore(Resource):340 @require_authentication341 def post(self, user_id):342 try:343 # check that the given user_id matches the logged in user id344 assert user_id == session['user']['id']345 except AssertionError:346 return {'errors': ['You are Unauthorized in this EP']}, u.HTTP_UNAUTHORIZED347 print('~~~~~ jobsSortBYscore ~~~~~')348 user = User.objects.get(pk=user_id)349 if len(user.cvs)==0:350 # print('len(user.cvs)', len(user.cvs))351 return None352 # findMatchWord2vec(user_id)353 # sorted(jobs_user.values(), reverse=True)354 # score_list = sorted(["{:.3f}".format(v) for k,v in jobs_user.items()],reverse=True)355 jobs_user = user.jobs356 # print('jobs_user: ', jobs_user)357 sorted_score = sorted(jobs_user.items(), key=operator.itemgetter(1), reverse=True)358 # print('sorted_score: ',sorted_score)359 response = {}360 for t in sorted_score:361 # job = t[0]362 job = Job.objects.get(identifier=t[0])363 response[t[0]] = (job.role_name, job.link,t[1],user.favorite[t[0]],user.sending[t[0]]364 ,user.replay[t[0]])365 print(response)366 return response367class jobsSortBYlocation(Resource):368 @require_authentication369 def post(self, user_id):370 try:371 # check that the given user_id matches the logged in user id372 assert user_id == session['user']['id']373 except AssertionError:374 return {'errors': ['You are Unauthorized in this EP']}, u.HTTP_UNAUTHORIZED375 print('~~~~~ jobsSortBYlocation ~~~~~')376 user = User.objects.get(pk=user_id)377 if len(user.cvs)==0:378 return None379 # findMatchWord2vec(user_id)380 cv_text = user.cvs[0].text381 # TODO: ××××ק ××× ×× ××©× × ×× ×פ×× ×§×¦×× ×©××צ×ת ×¢×ר ××ת ×× × ×פ×ת ×× ××שת×ש ×ש רש××ת ער×× ×©× ××תר ××¢×ר ××ת382 user_location = extract_location(cv_text)383 loc_dict = {}384 jobs_user = user.jobs385 # print('jobs_user: ', jobs_user)386 # to keep the location of job in dictionary387 for k,v in jobs_user.items():388 # job = Job.objects.get(identifier=k)389 city = one_city(k, user_location)390 loc_dict[k] = city391 #sort list of tuples (job_id,city) by order alphabet citie392 sorted_loc = sorted(loc_dict.items(), key=operator.itemgetter(1))393 # print('sorted_loc: ', sorted_loc)394 response = {}395 for s in sorted_loc:396 score = 0397 for k,v in jobs_user.items():398 if (s[0]==k):399 score = v400 break401 job = Job.objects.get(identifier=s[0])402 response[s[0]] = (job.role_name,job.link,score,s[1],user.favorite[s[0]],user.sending[s[0]]403 ,user.replay[s[0]])404 # print(response)405 return response406class UpdateFavorite(Resource):407 @require_authentication408 def post(self, user_id):409 try:410 # check that the given user_id matches the logged in user id411 assert user_id == session['user']['id']412 except AssertionError:413 return {'errors': ['You are Unauthorized in this EP']}, u.HTTP_UNAUTHORIZED414 print('------ post test ------')415 payload = request.json.get('body')416 job_id=payload.get('id')417 user = User.objects.get(id=user_id)418 if(user.favorite[job_id]==False):419 user.favorite[job_id]=True420 else:421 user.favorite[job_id]=False422 user.save()423class UpdateSending(Resource):424 @require_authentication425 def post(self, user_id):426 try:427 # check that the given user_id matches the logged in user id428 assert user_id == session['user']['id']429 except AssertionError:430 return {'errors': ['You are Unauthorized in this EP']}, u.HTTP_UNAUTHORIZED431 print('------ post test ------')432 payload = request.json.get('body')433 job_id=payload.get('id')434 user = User.objects.get(id=user_id)435 if(user.sending[job_id]==False):436 user.sending[job_id]=True437 # user.sendingDate[job_id]=datetime.datetime.now()438 user.sendingDate[job_id] = datetime.datetime.today()439 else:440 user.sending[job_id]=False441 if job_id in user.sendingDate:442 user.sendingDate.pop(job_id, None)443 user.save()444class UpdateReply(Resource):445 @require_authentication446 def post(self, user_id):447 try:448 # check that the given user_id matches the logged in user id449 assert user_id == session['user']['id']450 except AssertionError:451 return {'errors': ['You are Unauthorized in this EP']}, u.HTTP_UNAUTHORIZED452 payload = request.json.get('body')453 job_id = payload.get('id')454 user = User.objects.get(id=user_id)455 if (user.replay[job_id] == False):456 user.replay[job_id] = True457 user.replyDate[job_id] = datetime.datetime.today()458 else:459 user.replay[job_id] = False460 if job_id in user.replyDate:461 user.replyDate.pop(job_id, None)462 user.save()463class UserTimeLine(Resource):464 @require_authentication465 def post(self, user_id):466 try:467 # check that the given user_id matches the logged in user id468 assert user_id == session['user']['id']469 except AssertionError:470 return {'errors': ['You are Unauthorized in this EP']}, u.HTTP_UNAUTHORIZED471 print('~~~~~ UserTimeLine ~~~~~')472 user = User.objects.get(id=user_id)473 response = {}474 dates ={}475 if len(user.jobs)==0:476 # print('noJobs')477 return 'noJobs'478 if (len(user.sendingDate)==0 and len(user.replyDate)==0):479 # print('NoSendingReplyDate')480 return 'NoSendingReplyDate'481 # keep in dictionary key by date from sending dictionary482 for job in user.sendingDate:483 d = user.sendingDate[job].strftime("%d/%m/%Y")484 dic = {}485 if d not in dates:486 dates[d] = []487 j = Job.objects.get(identifier=job)488 dic[job]=j.role_name, 'SENT: CVs were sent to the employer'489 dates[d].append(dic)490 # keep in dictionary key by date from reply dictionary491 for job in user.replyDate:492 d = user.replyDate[job].strftime("%d/%m/%Y")493 dic = {}494 j = Job.objects.get(identifier=job)495 dic[job]=j.role_name,'REPLY: An employer came back'496 if d not in dates:497 dates[d] = []498 dates[d].append(dic)499 # to order by most new updated and return only 3 dates500 i=0501 for date in reversed(sorted(dates.keys())):502 i+=1503 response[date] = dates[date]504 if i==3:505 break;506 # print(response)507 return response508class PDFfile(Resource):509 @require_authentication510 def post(self,user_id):511 try:512 # check that the given user_id matches the logged in user id513 assert user_id == session['user']['id']514 except AssertionError:515 return {'errors': ['You are Unauthorized in this EP']}, u.HTTP_UNAUTHORIZED516 # print('------PDFfile----')517 payload = request.json.get('body')518 # print("payload - selectedFilter: ", payload['selectedFilter'])519 user = User.objects.get(id=user_id)520 filter_dict = {521 "0": "showAll",522 "1": "full",523 "2": "Half",524 "3": "student",525 "4": "sending",526 "5": "favorite",527 "6": "reply"528 }529 choice = str(payload['selectedFilter'])530 result = filter_dict[choice]531 # url=payload.get('urlFile')532 # receiver = user.email533 # print("receiver: " + receiver)534 # subject= 'This is the subject'535 # message='This is the message'536 # print(url)537 pdfFIle.send_user_mail(user, result)538class RegistersUserCounter(Resource):539 def get(self):540 print('~~~~~ In func GET in RegistersUserCounter ~~~~~')541 return len(User.objects)542class UsersFindJobCounter(Resource):543 def get(self):544 print('~~~~~ In func GET in UsersFindJobCounter ~~~~~')545 counter=0546 for i in User.objects():547 if i.find:548 counter=counter+1549 return counter550class UserContact(Resource):551 def post(self):552 payload = request.json553 name = payload.get('user_name')554 mail = payload.get('user_mail')555 message = payload.get('user_msg')556 fromaddr = config.MAIL_SENDER557 toaddr = config.MAIL_SENDER558 msg = MIMEMultipart()559 msg['To'] = toaddr560 msg['Subject'] = "User Contact - message"561 msg['From'] = fromaddr562 body = 'User Contact'563 msg.attach(MIMEText(body, 'plain'))564 output_filename = 'contact.pdf'565 options = {'quiet': ''}566 html = """567 <html>568 <head>569 <meta http-equiv="content-type" content="text/html"; charset="utf-8">570 </head>571 <body>572 <div class="message">573 <h3>User Name: %s</h3>574 <h3>User Mail: %s</h3>575 <p>User Message: %s</p>576 </div>577 </body>578 </html>579 """ % (name, mail, message)580 pdfkit.from_string(html, output_filename, css=['%s/utils/SOS/pdfContactStyle.css' % os.getcwd()],581 options=options)582 filename = "contact.pdf"583 attachment = open('contact.pdf', "rb")584 p = MIMEBase('application', 'octet-stream')585 p.set_payload(attachment.read())586 encoders.encode_base64(p)587 p.add_header('Content-Disposition', "attachment; filename= %s" % filename)588 msg.attach(p)589 server = smtplib.SMTP_SSL(config.MAIL_SERVER, config.MAIL_PORT)590 server.login(config.MAIL_SENDER, config.MAIL_PASSWORD)591 text = msg.as_string()592 server.sendmail(fromaddr, toaddr, text)593 server.quit()594 attachment.close()...
user.service.server.js
Source:user.service.server.js
1module.exports = function (app,model) {2 var bcrypt = require("bcrypt-nodejs");3 var passport=require('passport');4 var LocalStrategy=require('passport-local').Strategy;5 passport.use(new LocalStrategy(localStrategy));6 var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;7 passport.serializeUser(serializeUser);8 passport.deserializeUser(deserializeUser);9 var googleConfig = {10 clientID : "557184475880-tokdbetmhekop75uivafr862nnm7rcrl.apps.googleusercontent.com",11 clientSecret : "Og0AMs-3R33kucRAjoO69RU0",12 callbackURL : "http://sharma-karan-webdev.herokuapp.com/google/callback"13 // callbackURL : "http://localhost:3000/google/callback"14 };15 // var googleConfig = {16 // clientID : process.env.GOOGLE_CLIENT_ID,17 // clientSecret : process.env.GOOGLE_CLIENT_SECRET,18 // callbackURL : process.env.GOOGLE_CALLBACK_URL19 // };20 app.get("/api/user",findUser);21 app.post("/api/user",passport.authenticate('local'),login);// somebody to take this request, we want passport to take look at request22 app.post("/api/user/createUser",createUser);23 app.delete("/api/admin/user/:userId",deleteUser);24 app.get("/api/user/:userId",findUserById); // userId is the path paraameter25 app.put("/api/user/:userId",updateUser); // userId is the path paraameter26 // app.put("/api/user/:userId/search/:bookId",addToLibrary);27 app.get("/api/admin/:userId/viewLibrary/",getBooks);28 app.get("/api/user/userId/viewLibrary",getBooksFromLibrary);29 app.get("/api/usingObjects/user/:userId",findUserByIdUsingObjects);30 app.get("/api/get/Image/user/:userId",getImageLinkForUser);31 app.post('/api/user/isadmin',isAdmin);32 app.post('/api/user/isBuyer',isBuyer);33 app.post('/api/user/loggedin',loggedin);34 app.post("/api/user/logout", logout);35 app.post("/api/user/userId/viewLibrary",removeFromLibrary);36 app.post("/api/admin/createUser",createUserByAdmin);37 app.get("/api/admin/user",findAllUsers);38 app.post("/api/admin/user/:userId",updateUserByAdmin);39 app.post('/api/user/is/Seller',checkSeller);40 app.get('/google/callback',41 passport.authenticate('google', {42 successRedirect: '/project/#/user/viewProfile',43 failureRedirect: '/#'44 }));45 app.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email'] }));46 // app.get("/auth/google",function (req,res) {47 // console.log("login with google");48 // });49 app.get('/api/admin/user/:userId',findByIdUser);50 passport.use(new GoogleStrategy(googleConfig, googleStrategy));51 function googleStrategy(token, refreshToken, profile, done) {52 model.BookUserModel53 .findUserByGoogleId(profile.id)54 .then(55 function(user) {56 if(user) {57 return done(null, user);58 } else {59 var email = profile.emails[0].value;60 var emailParts = email.split("@");61 var newGoogleUser = {62 username: emailParts[0],63 password: emailParts[0],64 firstName: profile.name.givenName,65 lastName: profile.name.familyName,66 email: email,67 google: {68 id: profile.id,69 token: token70 }71 };72 return model.BookUserModel.createThroughGoogleUser(newGoogleUser);73 }74 },75 function(err) {76 if (err) { return done(err); }77 }78 )79 .then(80 function(user){81 return done(null, user);82 },83 function(err){84 if (err) { return done(err); }85 }86 );87 }88 function createUserByAdmin(req,res) {89 var user1 = req.body;90 var username = user1.username;91 console.log("username"+username);92 model.BookUserModel93 .findUserByUsername(username).then(94 function (user) {95 if (user) {96 console.log("user findbyusername"+user);97 res.send(400);98 }99 else {100 console.log("could not find user"+user1);101 model.BookUserModel.createUserByAdmin(user1).then(102 function (user1) {103 if(user1)104 {105 res.json(user1);106 }107 });108 }109 });110 }111 function login(req,res) { // next is for chaining the requests unitl somewhere the response is generated112 var user=req.user;113 console.log("inside login it is ");114 res.json(user);115 }116 function updateUserByAdmin(req,res)117 {118 var userId=req.params.userId;119 var user=req.body;120 user.password=bcrypt.hashSync(user.password);121 model.BookUserModel.updateUserByAdmin(userId,user)122 .then(function(user){123 res.json(user);124 });125 }126 function findByIdUser(req,res) {127 var userId=req.params.userId;128 model.BookUserModel129 .findUserById(userId)130 .then(131 function (user) {132 if(user)133 {134 res.json(user);135 }136 else137 {138 res.send(400);139 }140 }141 );142 }143 function localStrategy(username, password, done) {144 console.log(username);145 console.log(password);146 model.BookUserModel147 .findUserByCredentials(username, password)148 .then(149 function(user) {150 console.log('[0]');151 console.log(user);152 if (!user) {153 console.log('[1]');154 return done(null, false);155 }156 console.log('[2]');157 if(username && bcrypt.compareSync(password, user.password))158 {159 return done(null, user);160 }161 else162 {163 return done(null, false);164 }165 },166 function(err) {167 if (err) { return done(err); }168 }169 );170 }171 var q=require('q');172 var multer = require('multer');173 var upload = multer({ dest: __dirname+'/../../public/uploads' });174 app.post ("/api/upload", upload.single('myFile'), uploadImage);175 function uploadImage(req, res) {176 var myFile = req.file;177 var filename = myFile.filename;178 var widget = {};179 widget.url = req.protocol + '://' + req.get('host') + "/uploads/" + filename;180 console.log(widget.url);181 widget.width = req.body.width;182 var uId = req.body.userId;183 model.BookUserModel.updateImage(uId, widget).then(184 function (widget) {185 res.redirect("/project/#/user/editProfile");186 }187 , function (err) {188 res.sendStatus(500).send(err);189 });190 }191 function getImageLinkForUser(req,res) {192 var userId=req.params.userId;193 var uIds=req.body;194 console.log("isnide server "+uIds);195 model.BookUserModel196 .getImageLinkForUser(userId,uIds)197 .then(198 function(arrayLinks){199 res.json(arrayLinks);200 },201 function (error) {202 res.sendStatus(400).send(error);203 }204 );205 }206 function findUserByIdUsingObjects(req,res) {207 var userId=req.params.userId;208 model.BookUserModel209 .findUserByIdUsingObjects(userId)210 .then(function(user){211 res.json(user);212 });213 }214 function getBooksFromLibrary(req,res) {215 var userId=req.user._id;216 console.log("inside getbookfromlib");217 model.BookUserModel.getBooksFromLibrary(userId)218 .then(219 function (books) {220 console.log("inside server getting user with its library"+books);221 res.json(books);222 },223 function (error) {224 res.sendStatus(400).send(error);225 }226 );227 }228 function addToLibrary(req,res) {229 var userId=req.params.userId;230 console.log(userId);231 var bookEntry=req.body;232 console.log("inside server add to library"+bookEntry);233 model.BookUserModel.addToLibrary(bookEntry,userId)234 .then(235 function (bookEntry) {236 console.log("inside server add to library"+bookEntry);237 res.json(bookEntry);238 },239 function (error) {240 res.sendStatus(400).send(error);241 });242 }243 function deleteUser(req,res) {244 var userId=req.params.userId;245 model.BookUserModel.deleteUser(userId)246 .then(247 function (status) {248 res.send(200);249 },250 function (error) {251 res.sendStatus(400).send(error);252 });253 }254 function findUser(req,res) {255 var username=req.query.username;256 var password=req.query.password;257 if(username && password)258 {259 console.log("get only username and pass");260 findUserByCredentials(req,res);261 }262 else if(username)263 {264 console.log("get only username ");265 findUserByUsername(req,res);266 }267 }268 function createUser(req, res) {269 var newUser=req.body;270 newUser.firstName="New User";271 newUser.lastName="New User lastname";272 newUser.password=bcrypt.hashSync(newUser.password);273 model.BookUserModel274 .createUser(newUser)275 .then(function(newUser){276 req.login(newUser,function (err) {277 if(err)278 {279 console.log("inside create user error encountered "+err);280 res.send(400);281 }282 else283 {284 res.json(newUser);285 }286 });287 }, function (err) {288 res.sendStatus(400).send(err);289 });290 }291 function findUserByUsername(req,res) {292 var username=req.query.username;293 model.BookUserModel294 .findUserByUsername(username)295 .then(function(user,err){296 if(user)297 {298 console.log("in this succ"+user);299 res.json(user);300 }301 else302 {303 console.log("in this fail"+err);304 res.sendStatus(400).send(err);305 }306 });307 }308 function updateUser(req,res) {309 // var userId=req.params.userId;310 var userId=req.user._id;311 var newUser=req.body;312 newUser.password=bcrypt.hashSync(newUser.password);313 model.BookUserModel314 .updateUser(userId,newUser)315 .then(function(newUser){316 res.json(newUser);317 });318 }319 function findUserById(req, res)320 {321 // var userId=req.params.userId;322 var userId=req.user._id;323 console.log("serveer"+userId);324 model.BookUserModel325 .findUserById(userId)326 .then(function(user){327 res.json(user);328 });329 }330 function findUserByCredentials(req, res) {331 //res is the object used to genenrate the response332 //req represents everything coming from client333 var username=req.query.username;334 var password=req.query.password;335 console.log("Get the user by credentials fubp");336 model.BookUserModel337 .findUserByCredentials(username,password).then(338 function (user) {339 if(username && bcrypt.compareSync(password, user.password))340 {341 console.log("bcrypt working ");342 res.json(user);343 }344 },function (err) {345 res.send(err);346 }347 );}348 function serializeUser(user, done) {349 done(null, user);350 }351 function deserializeUser(user, done) {352 model.BookUserModel353 .findUserById(user._id)354 .then(355 function(user){356 console.log("serial"+user);357 done(null, user);358 },359 function(err){360 console.log(err);361 done(err, null);362 }363 );364 }365 function loggedin(req,res) {366 res.send(req.isAuthenticated() ? req.user : '0');367 // res.send('0');368 }369 function logout(req,res) {370 console.log("inside logout");371 req.logout();372 res.sendStatus(200);373 }374 function isAdmin(req,res) {375 res.send(req.isAuthenticated() && req.user.role=="ADMIN"? req.user : '0');376 }377 function findAllUsers(req,res) {378 if(req.user && req.user.role=='ADMIN')379 {380 model.BookUserModel381 .findAllUsers()382 .then(383 function(users){384 res.json(users);385 },386 function(err){387 res.send(400);388 }389 );390 }391 else392 {393 res.send(401);394 }395 }396 function removeFromLibrary(req,res) {397 var obj=req.body;398 var bookId=obj.bookId;399 var userId=obj.userId;400 //var userId=req.user._id;401 console.log("book id is server "+bookId);402 model.BookModel.getIdFromGoogleBookId(bookId).then(403 function (id) {404 console.log("id is "+id);405 model.BookUserModel.removeFromLibrary(id._id,userId)406 .then(407 function (user) {408 res.json(user);409 }410 );411 });412 }413 // // var userid=model.BookUserModel.getUserId(userId);414 // console.log("id returned from bookmodel is "+userId);415 // console.log("idbook returned from bookmodel is "+x);416 //417 // model.BookUserModel.removeFromLibrary(x._id,userId)418 // .then(419 //420 // function (user) {421 // res.json(user);422 // }423 // )424 function isBuyer(req,res) {425 res.send(req.isAuthenticated() && req.user.role=="BUYER"? req.user : '0');426 }427 function checkSeller(req,res)428 {429 res.send(req.isAuthenticated() && req.user.role=="SELLER"? req.user : '0');430 }431 function getBooks(req,res)432 {433 var obj=req.body;434 console.log(obj.someUserId);435 // console.log(obj);436 // var someUserId=obj.someUserId;437 var someUserId=req.params.userId;438 console.log(someUserId);439 model.BookUserModel.getBooksFromLibrary(someUserId)440 .then(441 function (books) {442 console.log("inside server getting user with its library"+books);443 res.json(books);444 },445 function (error) {446 res.sendStatus(400).send(error);447 }448 );449 }...
controller.ts
Source:controller.ts
...105 }106 },107 },108 Query: {109 async user(_: any, { userId }: any, ctx: Context): Promise<UserSource|null> {110 return await getUserSourceById(ctx, userId)111 },112 async currentUser(_: any, args: any, ctx: Context): Promise<UserSource|null> {113 if (ctx.user.id != null) {114 return await getUserSourceById(ctx, ctx.user.id)115 }116 return null117 },118 async allUsers(_: any, { query }: any, ctx: Context): Promise<UserSource[]|null> {119 if (ctx.isAdmin) {120 const users = await ctx.entityManager.getRepository(UserModel)121 .createQueryBuilder('user')122 .where('user.name ILIKE \'%\' || :query || \'%\'', { query })123 .orWhere('user.email ILIKE :query || \'%\'', { query })...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!