noogle: zaps in recommendation feeds

This commit is contained in:
Believethehype 2024-03-09 20:17:48 +01:00
parent c7d48b2997
commit c80275b74c
6 changed files with 271 additions and 107 deletions

View File

@ -41,7 +41,7 @@ async function generate_image(message) {
}
if(store.state.pubkey === undefined){
miniToastr.showMessage("Please login first", "No pubkey set", VueNotifications.types.warn)
return
}
@ -184,7 +184,7 @@ async function listen() {
let lud16 = current.profile.lud16
if (lud16 !== null && lud16 !== ""){
console.log("LUD16: " + lud16)
jsonentry.bolt11 = await createBolt11Lud16(lud16, jsonentry.amount)
jsonentry.bolt11 = await createBolt11Lud16(lud16, jsonentry.amount) //todo replace with zaprequest
console.log(jsonentry.bolt11)
if(jsonentry.bolt11 === ""){
status = "error"

View File

@ -4,7 +4,7 @@
:items="data"
:sort-by="sortBy"
:sort-type="sortType">
<template #item-content="{content, author, authorurl, avatar, indicator, links, lud16, id, authorid}">
<template #item-content="{content, author, authorurl, avatar, indicator, links, lud16, id, authorid, zapped, zapAmount}">
<div class="playeauthor-wrapper">
@ -28,21 +28,25 @@
<!--<a class="menusmall" :href="links.highlighter" target="_blank">Highlighter</a> -->
<a class="menusmall":href="links.nostrudel" target="_blank">Nostrudel</a>
<!--<div style="margin-left: auto; margin-right: 10px;" class=" justify-end mt-auto" @click="zap(lud16, id.toHex(), authorid)">
<svg style="margin-top:3px" xmlns="http://www.w3.org/2000/svg" width="14" height="16" fill="currentColor" class="bi bi-lightning" viewBox="0 0 16 20">
<path d="M5.52.359A.5.5 0 0 1 6 0h4a.5.5 0 0 1 .474.658L8.694 6H12.5a.5.5 0 0 1 .395.807l-7 9a.5.5 0 0 1-.873-.454L6.823 9.5H3.5a.5.5 0 0 1-.48-.641zM6.374 1 4.168 8.5H7.5a.5.5 0 0 1 .478.647L6.78 13.04 11.478 7H8a.5.5 0 0 1-.474-.658L9.306 1z"/></svg></div>-->
<div class="flex" v-if="!zapped" @click="zap(lud16, id, authorid, author)">
<div style="margin-left: auto; margin-right: 5px; float: left;">
<svg style="margin-top:4px" xmlns="http://www.w3.org/2000/svg" width="14" height="16" fill="currentColor" class="bi bi-lightning" viewBox="0 0 16 20">
<path d="M5.52.359A.5.5 0 0 1 6 0h4a.5.5 0 0 1 .474.658L8.694 6H12.5a.5.5 0 0 1 .395.807l-7 9a.5.5 0 0 1-.873-.454L6.823 9.5H3.5a.5.5 0 0 1-.48-.641zM6.374 1 4.168 8.5H7.5a.5.5 0 0 1 .478.647L6.78 13.04 11.478 7H8a.5.5 0 0 1-.474-.658L9.306 1z"/> </svg> </div>
<div>
<p style="float: left;">{{zapAmount/1000}}</p>
</div>
</div>
<div class="flex" v-if="zapped" @click="zap(lud16, id, authorid, author)" >
<div style="margin-left: auto; margin-right: 5px;">
<svg style="margin-top:4px" xmlns="http://www.w3.org/2000/svg" width="14" height="16" class="bi bi-lightning fill-amber-400" viewBox="0 0 16 20">
<path d="M5.52.359A.5.5 0 0 1 6 0h4a.5.5 0 0 1 .474.658L8.694 6H12.5a.5.5 0 0 1 .395.807l-7 9a.5.5 0 0 1-.873-.454L6.823 9.5H3.5a.5.5 0 0 1-.48-.641zM6.374 1 4.168 8.5H7.5a.5.5 0 0 1 .478.647L6.78 13.04 11.478 7H8a.5.5 0 0 1-.474-.658L9.306 1z"/></svg></div>
<div>
<p style="float: left;" className="text-amber-400">{{zapAmount/1000}}</p>
</div>
</div>
</div>
</template>
<!--<template #expand="item">
<div style="padding: 15px; text-align: left;" >
<a class="menu" :href="item.links.uri" target="_blank">Nostr Client</a>
<a class="menu" :href="item.links.njump" target="_blank">NJump</a>
<a class="menu" :href="item.links.highlighter" target="_blank">Highlighter</a>
<a class="menu":href="item.links.nostrudel" target="_blank">Nostrudel</a>
</div>
</template> -->
</EasyDataTable>
@ -61,11 +65,14 @@ import Null = types.Null;
import StringUtil from "@/components/helper/string";
import {copyinvoice, createBolt11Lud16, parseandreplacenpubs, zaprequest} from "@/components/helper/Helper.vue";
import {requestProvider} from "webln";
defineProps<{
data?: []
const props = defineProps<{
data: any[]
}>()
const sortBy: String = "index";
const sortType: SortType = "asc";
@ -75,12 +82,11 @@ const headers: Header[] = [
];
async function zap(lud16, id, authorid){
//let invoice = await zaprequest(lud16, 21 , "with love from noogle.lol", id, authorid, store.state.relays) //Not working yet
async function zap(lud16, eventid, authorid, author){
if(lud16 != Null && lud16 != ""){
let invoice = await createBolt11Lud16(lud16, 21)
let invoice = await zaprequest(lud16, 21 , "with love from noogle.lol", eventid, authorid, store.state.relays) //Not working yet
// let invoice = await createBolt11Lud16(lud16, 21)
let webln;
try {
webln = await requestProvider();
@ -90,6 +96,29 @@ async function zap(lud16, id, authorid){
if (webln) {
try{
let response = await webln.sendPayment(invoice)
if(response.preimage != null && response.preimage != ""){
let objects = (props.data.find(x=> x.id === eventid))
if (objects !== undefined){
console.log(objects.zapped)
objects.zapped = true
objects.zapAmount += 21000
}
/* if (objects != undefined && objects.length > 0){
console.log(objects[0])
props.data.find(x=> x.id === eventid).zapped.push.apply(props.data.find(x=> x.id === eventid).zapped, true)
}*/
// miniToastr.showMessage("Zapped " + author , "Success" , VueNotifications.types.warn)
console.log(response)
}
}
catch(err){

View File

@ -22,7 +22,7 @@ import {data} from "autoprefixer";
import {requestProvider} from "webln";
import Newnote from "@/components/Newnote.vue";
import SummarizationGeneration from "@/components/SummarizationGeneration.vue"
import {post_note, schedule, copyurl, copyinvoice, sleep, getEvents, get_user_infos, nextInput, createBolt11Lud16, getEventsOriginalOrder, parseandreplacenpubsName} from "../components/helper/Helper.vue"
import {post_note, schedule, copyurl, copyinvoice, sleep, getEvents, get_user_infos, get_zaps, nextInput, createBolt11Lud16, getEventsOriginalOrder, parseandreplacenpubsName} from "../components/helper/Helper.vue"
import amberSignerService from "./android-signer/AndroidSigner";
import StringUtil from "@/components/helper/string.ts";
@ -202,53 +202,75 @@ async function listen() {
}
const events = await getEventsOriginalOrder(entries)
let authors = []
for (const evt of events) {
for (const evt of events) {
try{
authors.push(evt.author)
}
catch(error){
console.log(error)
}
}
if (authors.length > 0) {
let profiles = await get_user_infos(authors)
try{
let profiles = await get_user_infos(authors)
let ids = []
for (let evt of events){
ids.push(evt.id)
}
let zaps = await get_zaps(ids)
let items = []
let index = 0
for (const evt of events) {
let p = profiles.find(record => record.author === evt.author.toHex())
let bech32id = evt.id.toBech32()
let nip19 = new Nip19Event(evt.id, evt.author, store.state.relays)
let nip19bech32 = nip19.toBech32()
let picture = p === undefined ? "../assets/nostr-purple.svg" : p["profile"]["picture"]
let name = p === undefined ? bech32id : p["profile"]["name"]
let authorid = evt.author.toHex()
let highlighterurl = "https://highlighter.com/e/" + nip19bech32
let njumpurl = "https://njump.me/" + nip19bech32
let nostrudelurl = "https://nostrudel.ninja/#/n/" + bech32id
let uri = "nostr:" + bech32id // nip19.toNostrUri()
let lud16 = "" //"p["profile"]["lud16"]"
for (const evt of events) {
if(!evt){
continue
}
let p = profiles.find(record => record.author === evt.author.toHex())
let bech32id = evt.id.toBech32()
let nip19 = new Nip19Event(evt.id, evt.author, store.state.relays)
let nip19bech32 = nip19.toBech32()
let picture = p === undefined ? "../assets/nostr-purple.svg" : p["profile"]["picture"]
let name = p === undefined ? bech32id : p["profile"]["name"]
let authorid = evt.author.toHex()
let highlighterurl = "https://highlighter.com/e/" + nip19bech32
let njumpurl = "https://njump.me/" + nip19bech32
let nostrudelurl = "https://nostrudel.ninja/#/n/" + bech32id
let uri = "nostr:" + bech32id // nip19.toNostrUri()
let lud16 = p === undefined ? "" : (p["profile"] === undefined ? "" : p["profile"]["lud16"])
if (items.find(e => e.id.toHex() === evt.id.toHex()) === undefined) {
items.push({
id: evt.id,
content: await parseandreplacenpubsName(evt.content),
author: name,
authorid: authorid,
authorurl: "https://njump.me/" + evt.author.toBech32(),
links: {
"uri": uri,
"highlighter": highlighterurl,
"njump": njumpurl,
"nostrudel": nostrudelurl
},
avatar: picture,
index: index,
indicator: {"time": evt.createdAt.toHumanDatetime(), "index": index},
lud16: lud16,
if (items.find(e => e.id === evt.id.toHex()) === undefined) {
items.push({
id: evt.id.toHex(),
content: await parseandreplacenpubsName(evt.content),
author: name,
authorid: authorid,
authorurl: "https://njump.me/" + evt.author.toBech32(),
links: {
"uri": uri,
"highlighter": highlighterurl,
"njump": njumpurl,
"nostrudel": nostrudelurl
},
avatar: picture,
index: index,
indicator: {"time": evt.createdAt.toHumanDatetime(), "index": index},
lud16: lud16,
zapped: zaps.find(x => x.id === evt.id.toHex()).zappedbyUser,
zapAmount: zaps.find(x => x.id === evt.id.toHex()).amount
})
index = index + 1
}
})
index = index+1
}
}
if (dvms.find(i => i.id === event.author.toHex()) === undefined){
if (dvms.find(i => i.id === event.author.toHex()) === undefined) {
await addDVM(event)
console.log("add dvm because of bug")
}
@ -257,8 +279,10 @@ async function listen() {
dvms.find(i => i.id === event.author.toHex()).result.length = 0
dvms.find(i => i.id === event.author.toHex()).result.push.apply(dvms.find(i => i.id === event.author.toHex()).result, items)
dvms.find(i => i.id === event.author.toHex()).status = "finished"
}
}
catch(error){
console.log(error)}
}
}
store.commit('set_recommendation_dvms', dvms)
}
@ -285,20 +309,20 @@ async function addAllContentDVMs(){
for (const tag of JSON.parse(el.event).tags){
if (tag[0] === "k" && tag[1] === "5300"){
console.log(el)
const filtera = new Filter().author(PublicKey.parse(el.id)).kinds([6300, 7000]).limit(1)
let client = store.state.client
let activities = await client.getEventsOf([filtera], Duration.fromSecs(1))
let last_active = 0
for (let activity of activities){
console.log(activity.createdAt.asSecs())
//console.log(activity.createdAt.asSecs())
if (activity.createdAt.asSecs() > last_active){
last_active = activity.createdAt.asSecs()
}
}
console.log(last_active)
// console.log(last_active)
// If DVM hasnt been active for 3 weeks, don't consider it.
if(last_active < Timestamp.now().asSecs() - 60*60*24*7){
continue

View File

@ -5,6 +5,8 @@ import amberSignerService from "@/components/android-signer/AndroidSigner";
import {Duration, Event, EventBuilder, EventId, Filter, Keys, PublicKey, Tag, Timestamp} from "@rust-nostr/nostr-sdk";
import miniToastr from "mini-toastr/mini-toastr";
import VueNotifications from "vue-notifications";
import {bech32} from "bech32";
export default defineComponent({
@ -136,7 +138,62 @@ export async function get_user_infos(pubkeys){
return profiles
}
export async function get_zaps(ids){
let zaps = []
let jsonentry = {}
for (let id of ids){
zaps.push({
id: id.toHex(),
amount: 0,
zappedbyUser: false,})
}
let client = store.state.client
const zap_filter = new Filter().kind(9735).events(ids)
let evts = await client.getEventsOf([zap_filter], Duration.fromSecs(10))
for (const entry of evts){
try{
//let contentjson = JSON.parse(entry.content)
for (let tag of entry.tags){
if (tag.asVec()[0] === "description"){
let request = JSON.parse(tag.asVec()[1])
let etag = ""
let amount = 0
for (let tg of request.tags){
if (tg[0] === "amount") {
amount = parseInt(tg[1])
}
if (tg[0] === "e") {
etag = tg[1]
console.log(request.pubkey )
if(request.pubkey === localStorage.getItem("nostr-key")){
zaps.find(x=> x.id === etag).zappedbyUser = true
}
}
}
zaps.find(x=> x.id === etag).amount += amount
}
}
//console.log(contentjson)
//zaps.push({profile: contentjson, author: entry.author.toHex(), createdAt: entry.createdAt});
}
catch(error){
console.log("error")
}
}
console.log(zaps)
return zaps
}
@ -159,17 +216,19 @@ export const sleep = (ms) => {
export async function parseandreplacenpubs(note){
note = note.replace("\n", " ")
const myArray = note.split(" ");
let finalnote = ""
for (let word in myArray){
if(myArray[word].startsWith("nostr:npub")){
//console.log(myArray[word])
if(myArray[word].startsWith("nostr:npub")){
console.log(myArray[word])
//console.log(pk.toBech32())
try{
let pk = PublicKey.parse(myArray[word].replace("nostr:", ""))
let profiles = await get_user_infos([pk])
console.log(profiles)
//console.log(profiles[0].profile.nip05)
myArray[word] = profiles[0].profile.nip05 // replace with nip05 for now
}
@ -184,9 +243,7 @@ export async function parseandreplacenpubs(note){
return finalnote.trimEnd()
}
var getHtmlBlock = function(dataType) {
return `<div class="icon negative big toleft" id="cancel-btn"><i class="fas fa-minus-circle"></i></div><div class="icon add big toleft"><i class="fas fa-check-circle"></i></div><input type="text" class="contact-input" style="margin-bottom: 5px;" maxlength="50" name="my-contact-phone" data-name="Name" placeholder="${dataType}">`;
};
export async function parseandreplacenpubsName(note){
const myArray = note.split(" ");
@ -217,26 +274,65 @@ export async function parseandreplacenpubsName(note){
return finalnote.trimEnd()
}
async function fetchAsync (url) {
let response = await fetch(url);
let data = await response.json();
return data;
}
export async function zaprequest(lud16, amount, content, zapped_event_id, zapped_user_id, relay_list){
let url = ""
if (lud16.toString().includes('@')){
url = 'https://' + lud16.toString().split('@')[1] + '/.well-known/lnurlp/' + lud16.toString().split('@')[0]
console.log(lud16)
console.log(PublicKey.parse(zapped_user_id).toBech32())
console.log(EventId.parse(zapped_event_id).toBech32())
console.log(zapped_event_id)
zapped_user_id = PublicKey.parse(zapped_user_id).toHex()
zapped_event_id = EventId.parse(zapped_event_id).toHex()
//overwrite for debug
//lud16 = "hype@bitcoinfixesthis.org"
//zapped_user_id = PublicKey.parse("npub1nxa4tywfz9nqp7z9zp7nr7d4nchhclsf58lcqt5y782rmf2hefjquaa6q8").toHex()
//zapped_event_id = EventId.parse("note1xsw95cp4ynelxdujd3xrh6kmre3y0lk699xn09z52mjenmktdllq9vtwyn").toHex()
if (lud16 !== "" && lud16.toString().includes('@')){
url = `https://${lud16.split('@')[1]}/.well-known/lnurlp/${lud16.split('@')[0]}`;
console.log(url)
}
else{
return None
return null
}
try{
let response = await fetch(url)
let ob = JSON.parse(response.content)
let ob = await fetchAsync(url)
let callback = ob["callback"]
let encoded_lnurl = "" // lnurl.encode(url)
let amount_tag = Tag.parse(['amount', (amount * 1000).toString()])
let relays_tag = Tag.parse(['relays', (relay_list).toString()])
let lnurl_tag = Tag.parse(['lnurl', encoded_lnurl])
let tags = []
console.log(callback)
const urlBytes = new TextEncoder().encode(url);
const encoded_lnurl = bech32.encode('lnurl', bech32.toWords(urlBytes), 1023);
console.log(encoded_lnurl)
console.log( relay_list.toString())
console.log(zapped_event_id)
console.log(zapped_user_id)
const amount_tag = Tag.parse(['amount', (amount * 1000).toString()]);
let relays = ['relays']
relays.push.apply(relays, relay_list)
let relays_tag = Tag.parse(relays);
const lnurl_tag = Tag.parse(['lnurl', encoded_lnurl]);
let tags
let p_tag = Tag.parse(['p', zapped_user_id])
if (zapped_event_id !== None){
if (zapped_event_id !== null){
let e_tag = Tag.parse(['e', zapped_event_id])
tags = [amount_tag, relays_tag, p_tag, e_tag, lnurl_tag]
}
@ -244,40 +340,56 @@ export async function zaprequest(lud16, amount, content, zapped_event_id, zapped
else{
tags = [amount_tag, relays_tag, p_tag, lnurl_tag]
}
//todo
/* if zaptype == "private":
key_str = keys.secret_key().to_hex() + zapped_event.id().to_hex() + str(zapped_event.created_at().as_secs())
encryption_key = sha256(key_str.encode('utf-8')).hexdigest()
zap_request = EventBuilder(9733, content,
[p_tag, e_tag]).to_event(keys).as_json()
keys = Keys.parse(encryption_key)
encrypted_content = enrypt_private_zap_message(zap_request, keys.secret_key(), zapped_event.author())
anon_tag = Tag.parse(['anon', encrypted_content])
tags.append(anon_tag)
content = "" */
/*if (zaptype === "private") {
const key_str = keys.secret_key().to_hex() + zapped_event.id().to_hex() + zapped_event.created_at().as_secs().toString();
const encryption_key = sha256(key_str).toString('hex');
const zap_request = new EventBuilder(9733, content, [p_tag, e_tag]).to_event(keys).as_json();
keys = Keys.parse(encryption_key);
const encrypted_content = enrypt_private_zap_message(zap_request, keys.secret_key(), zapped_event.author());
const anon_tag = Tag.parse(['anon', encrypted_content]);
tags.push(anon_tag);
content = "";
} */
let client = store.state.client
let zap_request = client.EventBuilder(9734, content,
tags).toSignedEvent().asJson()
let signer = store.state.signer
response = await fetch(callback + "?amount=" + (Number.parse(amount) * 1000).toString() + "&nostr=" + encodeURI(zap_request) + "&lnurl=" + encoded_lnurl)
ob = JSON.parse(response.content)
let noteevent = new EventBuilder(9734, content, tags).toUnsignedEvent(store.state.pubkey)
let signedEvent = await signer.signEvent(noteevent)
let zap_request = signedEvent.asJson()
//console.log(encoded_zap_request)
//`amount=${(amount * 1000).toString()}&nostr=${encodeURIComponent(zap_request)}&lnurl=${encoded_lnurl}`;
// const queryString = `amount=${(amount * 1000).toString()}&nostr=${encodeURIComponent(zap_request)}&lnurl=${encoded_lnurl}`;
try{
const queryString = `amount=${(amount * 1000).toString()}&nostr=${encodeURIComponent(zap_request)}&lnurl=${encoded_lnurl}`;
console.log(queryString)
let ob = await fetchAsync(`${callback}?${queryString}`)
return ob["pr"]
}
catch(e){
console.log("HELLO" + e)
}
}
catch(error){
console.log("ZAP REQUEST: " + e)
console.log("ZAP REQUEST: " + error)
}
return None
return null
}
export async function createBolt11Lud16(lud16, amount) {
if (lud16 === null || lud16 === ""){
return null;
}
let url;
if (lud16.includes('@')) { // LNaddress
const parts = lud16.split('@');

View File

@ -1,6 +1,7 @@
const Regex_Url_Str = "^https?:\/\/(?:.*\/)?[^\/.]+$" // domain name
const Regex_Url_Img = "(https?:\\/\\/.*\\.(?:png|jpg|jpeg|webp|gif))" // domain name
const Regex_Url_Video = "(https?:\\/\\/.*\\.(?:mp4|mov|avi))" // domain name
const Regex_Urlw_Str = "(https:\\/\\/)"+ "((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,})+[\\/]{0,1}" // domain name
;
@ -8,7 +9,7 @@ const Regex_Nip05_Str= "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^
const StringUtil = {
isValidUrl: (str: string): boolean => new RegExp(Regex_Url_Str, "i").test(str),
parseHyperlinks: (str: string): string => str.replace(new RegExp(Regex_Url_Str, "gim"), "<a class='purple' target=\"_blank\" rel=\"noreferrer\" href=\"$&\">$&</a>").replace(new RegExp(Regex_Nip05_Str, "gim"), "<a class='purple' target=\"_blank\" rel=\"noreferrer\" href=\"https://njump.me/$&\">$&</a>"),
parseHyperlinks: (str: string): string => str.replace(new RegExp(Regex_Urlw_Str, "gim"), "<a class='purple' target=\"_blank\" rel=\"noreferrer\" href=\"$&\">$&</a>").replace(new RegExp(Regex_Nip05_Str, "gim"), "<a class='purple' target=\"_blank\" rel=\"noreferrer\" href=\"https://njump.me/$&\">$&</a>"),
parseImages: (str: string): string => str.replace(new RegExp(Regex_Url_Img, "gim"), "<img src='$&'/> ").replace(new RegExp(Regex_Url_Video, "gim"), "<video controls muted autoplay src=\"$&\"></video>").replace(new RegExp(Regex_Url_Str, "gim"), "<a class='purple' target=\"_blank\" rel=\"noreferrer\" href=\"$&\">$&</a>"),

View File

@ -30,9 +30,7 @@ const store = createStore({
"wss://relay.damus.io",
"wss://nos.lol",
"wss://pablof7z.nostr1.com",
"wss://relay.nostr.net",
//"wss://relay.nostr.band",
//"wss://nostr-pub.wellorder.net",
"wss://relay.nostr.net"
],
}
},