From 56bd4d4f765e10d9c5574f6c88dbb00c67d486dc Mon Sep 17 00:00:00 2001 From: Believethehype <1097224+believethehype@users.noreply.github.com> Date: Thu, 11 Jul 2024 10:10:42 +0200 Subject: [PATCH] Fix for NIP88 Subscriptions, add non-follower content discovery --- nostr_dvm/dvm.py | 2 +- nostr_dvm/subscription.py | 2 +- ...iscovery_currently_popular_nonfollowers.py | 361 ++++++++++++++++++ nostr_dvm/utils/admin_utils.py | 2 +- nostr_dvm/utils/nip88_utils.py | 10 +- nostr_dvm/utils/nwc_tools.py | 14 +- setup.py | 2 +- tests/discovery.py | 124 +++++- tests/nwc.py | 7 +- tests/test_dvm_client.py | 4 +- tests/test_events.py | 73 ++-- 11 files changed, 542 insertions(+), 59 deletions(-) create mode 100644 nostr_dvm/tasks/content_discovery_currently_popular_nonfollowers.py diff --git a/nostr_dvm/dvm.py b/nostr_dvm/dvm.py index 5d963d6..2e5d76f 100644 --- a/nostr_dvm/dvm.py +++ b/nostr_dvm/dvm.py @@ -284,7 +284,7 @@ class DVM: async def handle_zap(zap_event): try: - invoice_amount, zapped_event, sender, message, anon = parse_zap_event_tags(zap_event, + invoice_amount, zapped_event, sender, message, anon = await parse_zap_event_tags(zap_event, self.keys, self.dvm_config.NIP89.NAME, self.client, self.dvm_config) diff --git a/nostr_dvm/subscription.py b/nostr_dvm/subscription.py index 092102f..72c4bc0 100644 --- a/nostr_dvm/subscription.py +++ b/nostr_dvm/subscription.py @@ -185,7 +185,7 @@ class Subscription: PublicKey.parse(zap[1]), self.keys, DVMConfig.RELAY_LIST) print(invoice) if invoice is not None: - nwc_event_id = nwc_zap(nwc, invoice, self.keys, zap[2]) + nwc_event_id = await nwc_zap(nwc, invoice, self.keys, zap[2]) if nwc_event_id is None: print("error zapping " + lud16) else: diff --git a/nostr_dvm/tasks/content_discovery_currently_popular_nonfollowers.py b/nostr_dvm/tasks/content_discovery_currently_popular_nonfollowers.py new file mode 100644 index 0000000..6381cac --- /dev/null +++ b/nostr_dvm/tasks/content_discovery_currently_popular_nonfollowers.py @@ -0,0 +1,361 @@ +import asyncio +import json +import os +from datetime import timedelta +from nostr_sdk import Client, Timestamp, PublicKey, Tag, Keys, Options, SecretKey, NostrSigner, NostrDatabase, \ + ClientBuilder, Filter, NegentropyOptions, NegentropyDirection, init_logger, LogLevel, Event, EventId, Kind, \ + RelayLimits + +from nostr_dvm.interfaces.dvmtaskinterface import DVMTaskInterface, process_venv +from nostr_dvm.utils import definitions +from nostr_dvm.utils.admin_utils import AdminConfig +from nostr_dvm.utils.definitions import EventDefinitions +from nostr_dvm.utils.dvmconfig import DVMConfig, build_default_config +from nostr_dvm.utils.nip88_utils import NIP88Config, check_and_set_d_tag_nip88, check_and_set_tiereventid_nip88 +from nostr_dvm.utils.nip89_utils import NIP89Config, check_and_set_d_tag, create_amount_tag +from nostr_dvm.utils.output_utils import post_process_list_to_events + +""" +This File contains a Module to discover popular notes by topics +Accepted Inputs: none +Outputs: A list of events +Params: None +""" + + +class DicoverContentCurrentlyPopularNonFollowers(DVMTaskInterface): + KIND: Kind = EventDefinitions.KIND_NIP90_CONTENT_DISCOVERY + TASK: str = "discover-content" + FIX_COST: float = 0 + dvm_config: DVMConfig + request_form = None + last_schedule: int + min_reactions = 2 + db_since = 10 * 3600 + db_name = "db/nostr_default_recent_notes.db" + search_list = [] + avoid_list = [] + must_list = [] + personalized = True + result = "" + + async def init_dvm(self, name, dvm_config: DVMConfig, nip89config: NIP89Config, nip88config: NIP88Config = None, + admin_config: AdminConfig = None, options=None): + + self.request_form = {"jobID": "generic"} + opts = { + "max_results": 200, + } + self.request_form['options'] = json.dumps(opts) + + dvm_config.SCRIPT = os.path.abspath(__file__) + + if self.options.get("personalized"): + self.personalized = bool(self.options.get("personalized")) + self.last_schedule = Timestamp.now().as_secs() + if self.options.get("search_list"): + self.search_list = self.options.get("search_list") + # print(self.search_list) + if self.options.get("avoid_list"): + self.avoid_list = self.options.get("avoid_list") + if self.options.get("must_list"): + self.must_list = self.options.get("must_list") + if self.options.get("db_name"): + self.db_name = self.options.get("db_name") + if self.options.get("db_since"): + self.db_since = int(self.options.get("db_since")) + + use_logger = False + if use_logger: + init_logger(LogLevel.DEBUG) + + if self.dvm_config.UPDATE_DATABASE: + await self.sync_db() + if not self.personalized: + self.result = await self.calculate_result(self.request_form) + + async def is_input_supported(self, tags, client=None, dvm_config=None): + for tag in tags: + if tag.as_vec()[0] == 'i': + input_value = tag.as_vec()[1] + input_type = tag.as_vec()[2] + if input_type != "text": + return False + return True + + async def create_request_from_nostr_event(self, event, client=None, dvm_config=None): + self.dvm_config = dvm_config + + request_form = {"jobID": event.id().to_hex()} + user = event.author().to_hex() + # default values + max_results = 200 + + for tag in event.tags(): + if tag.as_vec()[0] == 'i': + input_type = tag.as_vec()[2] + elif tag.as_vec()[0] == 'param': + param = tag.as_vec()[1] + if param == "max_results": # check for param type + max_results = int(tag.as_vec()[2]) + elif param == "user": # check for param type + user = tag.as_vec()[2] + + options = { + "max_results": max_results, + "user": user, + } + request_form['options'] = json.dumps(options) + self.request_form = request_form + return request_form + + async def process(self, request_form): + # if the dvm supports individual results, recalculate it every time for the request + if self.personalized: + return await self.calculate_result(request_form) + # else return the result that gets updated once every schenduled update. In this case on database update. + else: + return self.result + + async def post_process(self, result, event): + """Overwrite the interface function to return a social client readable format, if requested""" + for tag in event.tags(): + if tag.as_vec()[0] == 'output': + format = tag.as_vec()[1] + if format == "text/plain": # check for output type + result = post_process_list_to_events(result) + + # if not text/plain, don't post-process + return result + + async def calculate_result(self, request_form): + from nostr_sdk import Filter + from types import SimpleNamespace + ns = SimpleNamespace() + + options = self.set_options(request_form) + relaylimits = RelayLimits.disable() + opts = ( + Options().wait_for_send(True).send_timeout(timedelta(seconds=self.dvm_config.RELAY_TIMEOUT)).relay_limits( + relaylimits)) + sk = SecretKey.from_hex(self.dvm_config.PRIVATE_KEY) + keys = Keys.parse(sk.to_hex()) + signer = NostrSigner.keys(keys) + database = await NostrDatabase.sqlite(self.db_name) + + cli = ClientBuilder().database(database).signer(signer).opts(opts).build() + await cli.add_relay("wss://relay.damus.io") + await cli.add_relay("wss://nostr.oxtr.dev") + await cli.add_relay("wss://nostr.mom") + + # ropts = RelayOptions().ping(False) + # cli.add_relay_with_opts("wss://nostr.band", ropts) + + await cli.connect() + user = PublicKey.parse(options["user"]) + followers_filter = Filter().author(user).kinds([Kind(3)]) + followers = await cli.get_events_of([followers_filter], timedelta(seconds=self.dvm_config.RELAY_TIMEOUT)) + if len(followers) > 0: + newest = 0 + best_entry = followers[0] + for entry in followers: + if entry.created_at().as_secs() > newest: + newest = entry.created_at().as_secs() + best_entry = entry + + #print(best_entry.as_json()) + followings = [] + for tag in best_entry.tags(): + if tag.as_vec()[0] == "p": + following = tag.as_vec()[1] + followings.append(following) + else: + print("Couldn't find follower List") + return [] + + + + + timestamp_since = Timestamp.now().as_secs() - self.db_since + since = Timestamp.from_secs(timestamp_since) + + filter1 = Filter().kind(definitions.EventDefinitions.KIND_NOTE).since(since) + + events = await database.query([filter1]) + if self.dvm_config.LOGLEVEL.value >= LogLevel.DEBUG.value: + print("[" + self.dvm_config.NIP89.NAME + "] Considering " + str(len(events)) + " Events") + ns.finallist = {} + + for event in events: + if event.author().to_hex() in followings: + continue + + filt = Filter().kinds( + [definitions.EventDefinitions.KIND_ZAP, definitions.EventDefinitions.KIND_REACTION, + definitions.EventDefinitions.KIND_REPOST, + definitions.EventDefinitions.KIND_NOTE]).event(event.id()).since(since) + reactions = await database.query([filt]) + if len(reactions) >= self.min_reactions: + ns.finallist[event.id().to_hex()] = len(reactions) + + result_list = [] + finallist_sorted = sorted(ns.finallist.items(), key=lambda x: x[1], reverse=True)[:int(options["max_results"])] + for entry in finallist_sorted: + # print(EventId.parse(entry[0]).to_bech32() + "/" + EventId.parse(entry[0]).to_hex() + ": " + str(entry[1])) + e_tag = Tag.parse(["e", entry[0]]) + result_list.append(e_tag.as_vec()) + if self.dvm_config.LOGLEVEL.value >= LogLevel.DEBUG.value: + print("[" + self.dvm_config.NIP89.NAME + "] Filtered " + str( + len(result_list)) + " fitting events.") + #await cli.shutdown() + return json.dumps(result_list) + + async def schedule(self, dvm_config): + if dvm_config.SCHEDULE_UPDATES_SECONDS == 0: + return 0 + else: + if Timestamp.now().as_secs() >= self.last_schedule + dvm_config.SCHEDULE_UPDATES_SECONDS: + if self.dvm_config.UPDATE_DATABASE: + await self.sync_db() + self.last_schedule = Timestamp.now().as_secs() + return 1 + + async def sync_db(self): + opts = (Options().wait_for_send(False).send_timeout(timedelta(seconds=self.dvm_config.RELAY_LONG_TIMEOUT))) + sk = SecretKey.from_hex(self.dvm_config.PRIVATE_KEY) + keys = Keys.parse(sk.to_hex()) + signer = NostrSigner.keys(keys) + database = await NostrDatabase.sqlite(self.db_name) + cli = ClientBuilder().signer(signer).database(database).opts(opts).build() + + for relay in self.dvm_config.RECONCILE_DB_RELAY_LIST: + await cli.add_relay(relay) + + await cli.connect() + + timestamp_since = Timestamp.now().as_secs() - self.db_since + since = Timestamp.from_secs(timestamp_since) + + filter1 = Filter().kinds([definitions.EventDefinitions.KIND_NOTE, definitions.EventDefinitions.KIND_REACTION, + definitions.EventDefinitions.KIND_ZAP]).since(since) # Notes, reactions, zaps + + # filter = Filter().author(keys.public_key()) + if self.dvm_config.LOGLEVEL.value >= LogLevel.DEBUG.value: + print("[" + self.dvm_config.NIP89.NAME + "] Syncing notes of the last " + str( + self.db_since) + " seconds.. this might take a while..") + dbopts = NegentropyOptions().direction(NegentropyDirection.DOWN) + await cli.reconcile(filter1, dbopts) + await cli.database().delete(Filter().until(Timestamp.from_secs( + Timestamp.now().as_secs() - self.db_since))) # Clear old events so db doesn't get too full. + await cli.shutdown() + if self.dvm_config.LOGLEVEL.value >= LogLevel.DEBUG.value: + print( + "[" + self.dvm_config.NIP89.NAME + "] Done Syncing Notes of the last " + str(self.db_since) + " seconds..") + + +# We build an example here that we can call by either calling this file directly from the main directory, +# or by adding it to our playground. You can call the example and adjust it to your needs or redefine it in the +# playground or elsewhere +def build_example(name, identifier, admin_config, options, image, description, update_rate=600, cost=0, + processing_msg=None, update_db=True): + dvm_config = build_default_config(identifier) + dvm_config.USE_OWN_VENV = False + dvm_config.SHOWLOG = True + dvm_config.SCHEDULE_UPDATES_SECONDS = update_rate # Every 10 minutes + dvm_config.UPDATE_DATABASE = update_db + # Activate these to use a subscription based model instead + # dvm_config.SUBSCRIPTION_REQUIRED = True + # dvm_config.SUBSCRIPTION_DAILY_COST = 1 + dvm_config.FIX_COST = cost + dvm_config.CUSTOM_PROCESSING_MESSAGE = processing_msg + admin_config.LUD16 = dvm_config.LN_ADDRESS + + # Add NIP89 + nip89info = { + "name": name, + "image": image, + "picture": image, + "about": description, + "lud16": dvm_config.LN_ADDRESS, + "encryptionSupported": True, + "cashuAccepted": True, + "personalized": False, + "amount": create_amount_tag(cost), + "nip90Params": { + "max_results": { + "required": False, + "values": [], + "description": "The number of maximum results to return (default currently 100)" + } + } + } + + nip89config = NIP89Config() + nip89config.DTAG = check_and_set_d_tag(identifier, name, dvm_config.PRIVATE_KEY, nip89info["image"]) + nip89config.CONTENT = json.dumps(nip89info) + + return DicoverContentCurrentlyPopularNonFollowers(name=name, dvm_config=dvm_config, nip89config=nip89config, + admin_config=admin_config, options=options) + + +def build_example_subscription(name, identifier, admin_config, options, image, description, processing_msg=None, + update_db=True): + dvm_config = build_default_config(identifier) + dvm_config.USE_OWN_VENV = False + dvm_config.SHOWLOG = True + dvm_config.SCHEDULE_UPDATES_SECONDS = 600 # Every 10 minutes + dvm_config.UPDATE_DATABASE = update_db + # Activate these to use a subscription based model instead + dvm_config.FIX_COST = 0 + dvm_config.CUSTOM_PROCESSING_MESSAGE = processing_msg + admin_config.LUD16 = dvm_config.LN_ADDRESS + + # Add NIP89 + nip89info = { + "name": name, + "image": image, + "picture": image, + "about": description, + "lud16": dvm_config.LN_ADDRESS, + "encryptionSupported": True, + "cashuAccepted": True, + "subscription": True, + "personalized": False, + "nip90Params": { + "max_results": { + "required": False, + "values": [], + "description": "The number of maximum results to return (default currently 100)" + } + } + } + + nip89config = NIP89Config() + nip89config.DTAG = check_and_set_d_tag(identifier, name, dvm_config.PRIVATE_KEY, nip89info["image"]) + nip89config.CONTENT = json.dumps(nip89info) + + nip88config = NIP88Config() + nip88config.DTAG = check_and_set_d_tag_nip88(identifier, name, dvm_config.PRIVATE_KEY, nip89info["image"]) + nip88config.TIER_EVENT = check_and_set_tiereventid_nip88(identifier, "1") + nip89config.NAME = name + nip88config.IMAGE = nip89info["image"] + nip88config.TITLE = name + nip88config.AMOUNT_DAILY = 100 + nip88config.AMOUNT_MONTHLY = 2000 + nip88config.CONTENT = "Subscribe to the DVM for unlimited use during your subscription" + nip88config.PERK1DESC = "Unlimited requests" + nip88config.PERK2DESC = "Support NostrDVM & NostrSDK development" + nip88config.PAYMENT_VERIFIER_PUBKEY = "5b5c045ecdf66fb540bdf2049fe0ef7f1a566fa427a4fe50d400a011b65a3a7e" + + # admin_config.FETCH_NIP88 = True + # admin_config.EVENTID = "63a791cdc7bf78c14031616963105fce5793f532bb231687665b14fb6d805fdb" + # admin_config.PRIVKEY = dvm_config.PRIVATE_KEY + + return DicoverContentCurrentlyPopularNonFollowers(name=name, dvm_config=dvm_config, nip89config=nip89config, + nip88config=nip88config, + admin_config=admin_config, + options=options) + + +if __name__ == '__main__': + process_venv(DicoverContentCurrentlyPopularNonFollowers) diff --git a/nostr_dvm/utils/admin_utils.py b/nostr_dvm/utils/admin_utils.py index 9d5fb37..a198f17 100644 --- a/nostr_dvm/utils/admin_utils.py +++ b/nostr_dvm/utils/admin_utils.py @@ -97,7 +97,7 @@ async def admin_make_database_updates(adminconfig: AdminConfig = None, dvmconfig await nip65_announce_relays(dvmconfig, client=client) if adminconfig.REBROADCAST_NIP88: - annotier_id = nip88_announce_tier(dvmconfig, client=client) + annotier_id = await nip88_announce_tier(dvmconfig, client=client) check_and_set_tiereventid_nip88(dvmconfig.IDENTIFIER, adminconfig.INDEX, annotier_id.to_hex()) if adminconfig.DELETE_NIP89: diff --git a/nostr_dvm/utils/nip88_utils.py b/nostr_dvm/utils/nip88_utils.py index 58ddd9d..9dbf049 100644 --- a/nostr_dvm/utils/nip88_utils.py +++ b/nostr_dvm/utils/nip88_utils.py @@ -128,7 +128,7 @@ async def nip88_has_active_subscription(user: PublicKey, tiereventdtag, client: return subscription_status -def nip88_announce_tier(dvm_config, client): +async def nip88_announce_tier(dvm_config, client): title_tag = Tag.parse(["title", str(dvm_config.NIP88.TITLE)]) image_tag = Tag.parse(["image", str(dvm_config.NIP88.IMAGE)]) d_tag = Tag.parse(["d", dvm_config.NIP88.DTAG]) @@ -175,9 +175,13 @@ def nip88_announce_tier(dvm_config, client): keys = Keys.parse(dvm_config.NIP89.PK) content = dvm_config.NIP88.CONTENT event = EventBuilder(EventDefinitions.KIND_NIP88_TIER_EVENT, content, tags).to_event(keys) - annotier_id = send_event(event, client=client, dvm_config=dvm_config) + annotier_id = await send_event(event, client=client, dvm_config=dvm_config) + + if dvm_config.NIP89 is not None: + print("[" + dvm_config.NIP89.NAME + "] Announced NIP 88 Tier") + else: + print("[" + dvm_config.identifier + "] Announced NIP 88 Tier") - print("[" + dvm_config.NAME + "] Announced NIP 88 Tier for " + dvm_config.NIP89.NAME) return annotier_id diff --git a/nostr_dvm/utils/nwc_tools.py b/nostr_dvm/utils/nwc_tools.py index d4e869a..502a25b 100644 --- a/nostr_dvm/utils/nwc_tools.py +++ b/nostr_dvm/utils/nwc_tools.py @@ -11,19 +11,19 @@ from nostr_dvm.utils.nostr_utils import check_and_set_private_key from nostr_dvm.utils.zap_utils import zaprequest -def nwc_zap(connectionstr, bolt11, keys, externalrelay=None): +async def nwc_zap(connectionstr, bolt11, keys, externalrelay=None): uri = NostrWalletConnectUri.parse(connectionstr) # Initialize NWC client nwc = Nwc(uri) - info = nwc.get_info() + info = await nwc.get_info() print(info) - balance = nwc.get_balance() - print(f"Balance: {balance} SAT") + balance = await nwc.get_balance() + print(f"Balance: {balance} MilliSats") - event_id = nwc.pay_invoice(bolt11) + event_id = await nwc.pay_invoice(bolt11) print("NWC event: " + event_id) @@ -110,7 +110,7 @@ def make_nwc_account(identifier, nwcdomain): return "" -def nwc_test(nwc_server): +async def nwc_test(nwc_server): connectionstring = make_nwc_account("test", nwc_server + "/api/new") print(connectionstring) # TODO Store the connection string in a db, use here if you already have one @@ -124,4 +124,4 @@ def nwc_test(nwc_server): bolt11 = zaprequest("hype@bitcoinfixesthis.org", 21, "Cool Stuff", None, pubkey, keys, DVMConfig.RELAY_LIST) - nwc_zap(connectionstring, bolt11, keys) + await nwc_zap(connectionstring, bolt11, keys) diff --git a/setup.py b/setup.py index 0a1acc0..d58cdb3 100644 --- a/setup.py +++ b/setup.py @@ -1,6 +1,6 @@ from setuptools import setup, find_packages -VERSION = '0.6.33' +VERSION = '0.7.0' DESCRIPTION = 'A framework to build and run Nostr NIP90 Data Vending Machines' LONG_DESCRIPTION = ('A framework to build and run Nostr NIP90 Data Vending Machines. See the github repository for more information') diff --git a/tests/discovery.py b/tests/discovery.py index d0c8eaa..b32a739 100644 --- a/tests/discovery.py +++ b/tests/discovery.py @@ -7,6 +7,7 @@ import dotenv from nostr_sdk import init_logger, LogLevel, Keys, NostrLibrary from nostr_dvm.tasks.content_discovery_currently_latest_longform import DicoverContentLatestLongForm +from nostr_dvm.tasks.content_discovery_currently_popular_nonfollowers import DicoverContentCurrentlyPopularNonFollowers from nostr_dvm.tasks.content_discovery_update_db_only import DicoverContentDBUpdateScheduler #os.environ["RUST_BACKTRACE"] = "full" @@ -19,6 +20,7 @@ from nostr_dvm.tasks.discovery_trending_notes_nostrband import TrendingNotesNost from nostr_dvm.utils.admin_utils import AdminConfig from nostr_dvm.utils.dvmconfig import build_default_config, DVMConfig from nostr_dvm.utils.mediasource_utils import organize_input_media_data +from nostr_dvm.utils.nip88_utils import NIP88Config, check_and_set_d_tag_nip88, check_and_set_tiereventid_nip88 from nostr_dvm.utils.nip89_utils import create_amount_tag, NIP89Config, check_and_set_d_tag from nostr_dvm.utils.nostr_utils import check_and_set_private_key from nostr_dvm.utils.outbox_utils import AVOID_OUTBOX_RELAY_LIST @@ -307,6 +309,71 @@ def build_example_popular_followers(name, identifier, admin_config, options, ima options=options, admin_config=admin_config) +def build_example_popular_non_followers(name, identifier, admin_config, options, image, cost=0, update_rate=300, + processing_msg=None, update_db=True): + + + dvm_config = build_default_config(identifier) + dvm_config.USE_OWN_VENV = False + dvm_config.SHOWLOG = True + dvm_config.LOGLEVEL = LogLevel.DEBUG + dvm_config.SCHEDULE_UPDATES_SECONDS = update_rate # Every 10 minutes + dvm_config.UPDATE_DATABASE = update_db + # Activate these to use a subscription based model instead + dvm_config.FIX_COST = cost + dvm_config.CUSTOM_PROCESSING_MESSAGE = processing_msg + dvm_config.AVOID_PAID_OUTBOX_RELAY_LIST = AVOID_OUTBOX_RELAY_LIST + admin_config.LUD16 = dvm_config.LN_ADDRESS + admin_config.REBROADCAST_NIP88 = False + #admin_config.REBROADCAST_NIP89 = True + admin_config.UPDATE_PROFILE = True + + # Add NIP89 + nip89info = { + "name": name, + "image": image, + "picture": image, + "about": "I show notes that are currently popular from people you do not follow", + "lud16": dvm_config.LN_ADDRESS, + "encryptionSupported": True, + "cashuAccepted": True, + "subscription": True, + "personalized": False, + "nip90Params": { + "max_results": { + "required": False, + "values": [], + "description": "The number of maximum results to return (default currently 100)" + } + } + } + + nip89config = NIP89Config() + nip89config.DTAG = check_and_set_d_tag(identifier, name, dvm_config.PRIVATE_KEY, nip89info["image"]) + nip89config.CONTENT = json.dumps(nip89info) + + nip88config = NIP88Config() + nip88config.DTAG = check_and_set_d_tag_nip88(identifier, name, dvm_config.PRIVATE_KEY, nip89info["image"]) + nip88config.TIER_EVENT = check_and_set_tiereventid_nip88(identifier, "1") + nip89config.NAME = name + nip88config.IMAGE = nip89info["image"] + nip88config.TITLE = name + nip88config.AMOUNT_DAILY = 100 + nip88config.AMOUNT_MONTHLY = 2000 + nip88config.CONTENT = "Subscribe to the DVM for unlimited use during your subscription" + nip88config.PERK1DESC = "Unlimited requests" + nip88config.PERK2DESC = "Support NostrDVM & NostrSDK development" + nip88config.PAYMENT_VERIFIER_PUBKEY = "5b5c045ecdf66fb540bdf2049fe0ef7f1a566fa427a4fe50d400a011b65a3a7e" + + #admin_config.FETCH_NIP88 = True + #admin_config.EVENTID = "63a791cdc7bf78c14031616963105fce5793f532bb231687665b14fb6d805fdb" + admin_config.PRIVKEY = dvm_config.PRIVATE_KEY + + return DicoverContentCurrentlyPopularNonFollowers(name=name, dvm_config=dvm_config, nip89config=nip89config, + nip88config=nip88config, + admin_config=admin_config, + options=options) + def build_example_top_zapped(name, identifier, admin_config, options, image, cost=0, update_rate=180, processing_msg=None, @@ -599,6 +666,38 @@ def playground(): update_db=update_db) discovery_followers.run() + # Popular Followers + admin_config_nonfollowers = AdminConfig() + admin_config_nonfollowers.REBROADCAST_NIP89 = rebroadcast_NIP89 + admin_config_nonfollowers.REBROADCAST_NIP65_RELAY_LIST = rebroadcast_NIP65_Relay_List + admin_config_nonfollowers.UPDATE_PROFILE = update_profile + # admin_config_followers.DELETE_NIP89 = True + # admin_config_followers.PRIVKEY = "" + # admin_config_followers.EVENTID = "590cd7b2902224f740acbd6845023a5ab4a959386184f3360c2859019cfd48fa" + # admin_config_followers.POW = True + custom_processing_msg = ["Processing popular notes from npubs you don't follow..", + "Let's see what npubs outside of your circle have been up to..", + "Processing a personalized feed, just for you.."] + update_db = False + options_nonfollowers_popular = { + "db_name": "db/nostr_recent_notes.db", + "db_since": 2 * 60 * 60, # 2h since gmt, + } + cost = 0 + image = "https://i.nostr.build/l11EczDmpZBaxlRm.jpg" + + discovery_non_followers = build_example_popular_non_followers( + "Popular from npubs you don't follow", + "discovery_content_nonfollowers", + admin_config=admin_config_nonfollowers, + options=options_nonfollowers_popular, + cost=cost, + image=image, + update_rate=global_update_rate, + processing_msg=custom_processing_msg, + update_db=update_db) + discovery_non_followers.run() + # Popular Global admin_config_global_popular = AdminConfig() admin_config_global_popular.REBROADCAST_NIP89 = rebroadcast_NIP89 @@ -633,21 +732,20 @@ def playground(): # discovery_test_sub.run() # Subscription Manager DVM - # subscription_config = DVMConfig() - # subscription_config.PRIVATE_KEY = check_and_set_private_key("dvm_subscription") - # npub = Keys.parse(subscription_config.PRIVATE_KEY).public_key().to_bech32() - # invoice_key, admin_key, wallet_id, user_id, lnaddress = check_and_set_ln_bits_keys("dvm_subscription", npub) - # subscription_config.LNBITS_INVOICE_KEY = invoice_key - # subscription_config.LNBITS_ADMIN_KEY = admin_key # The dvm might pay failed jobs back - # subscription_config.LNBITS_URL = os.getenv("LNBITS_HOST") - # sub_admin_config = AdminConfig() - # sub_admin_config.USERNPUBS = ["7782f93c5762538e1f7ccc5af83cd8018a528b9cd965048386ca1b75335f24c6"] #Add npubs of services that can contact the subscription handler + subscription_config = DVMConfig() + subscription_config.PRIVATE_KEY = check_and_set_private_key("dvm_subscription") + npub = Keys.parse(subscription_config.PRIVATE_KEY).public_key().to_bech32() + invoice_key, admin_key, wallet_id, user_id, lnaddress = check_and_set_ln_bits_keys("dvm_subscription", npub) + subscription_config.LNBITS_INVOICE_KEY = invoice_key + subscription_config.LNBITS_ADMIN_KEY = admin_key # The dvm might pay failed jobs back + subscription_config.LNBITS_URL = os.getenv("LNBITS_HOST") + sub_admin_config = AdminConfig() + #sub_admin_config.USERNPUBS = ["7782f93c5762538e1f7ccc5af83cd8018a528b9cd965048386ca1b75335f24c6"] #Add npubs of services that can contact the subscription handler - # currently there is none, but add this once subscriptions are live. - # x = threading.Thread(target=Subscription, args=(Subscription(subscription_config, sub_admin_config),)) - # x.start() + x = threading.Thread(target=Subscription, args=(Subscription(subscription_config, sub_admin_config),)) + x.start() - # keep_alive() + # keep_alive() diff --git a/tests/nwc.py b/tests/nwc.py index 3a8c57b..932976b 100644 --- a/tests/nwc.py +++ b/tests/nwc.py @@ -1,3 +1,4 @@ +import asyncio import os from pathlib import Path @@ -9,13 +10,13 @@ from nostr_dvm.utils.nwc_tools import nwc_zap from nostr_dvm.utils.zap_utils import create_bolt11_lud16, zaprequest -def playground(): +async def playground(): connectionstr = os.getenv("TEST_NWC") keys = Keys.parse(os.getenv("TEST_USER")) bolt11 = zaprequest("bot@nostrdvm.com", 5, "test", None, PublicKey.parse("npub1cc79kn3phxc7c6mn45zynf4gtz0khkz59j4anew7dtj8fv50aqrqlth2hf"), keys, dvmconfig.DVMConfig.RELAY_LIST, zaptype="private") print(bolt11) - result = nwc_zap(connectionstr, bolt11, keys, externalrelay=None) + result = await nwc_zap(connectionstr, bolt11, keys, externalrelay=None) print(result) @@ -30,4 +31,4 @@ if __name__ == '__main__': dotenv.load_dotenv(env_path, verbose=True, override=True) else: raise FileNotFoundError(f'.env file not found at {env_path} ') - playground() \ No newline at end of file + asyncio.run(playground()) \ No newline at end of file diff --git a/tests/test_dvm_client.py b/tests/test_dvm_client.py index a1517ed..399ac81 100644 --- a/tests/test_dvm_client.py +++ b/tests/test_dvm_client.py @@ -300,14 +300,14 @@ async def nostr_client(): # await nostr_client_test_image("a beautiful purple ostrich watching the sunset") # await nostr_client_test_search_profile("dontbelieve") wot = ["99bb5591c9116600f845107d31f9b59e2f7c7e09a1ff802e84f1d43da557ca64"] - # aawait nostr_client_test_disovery("99bb5591c9116600f845107d31f9b59e2f7c7e09a1ff802e84f1d43da557ca64", "a21592a70ef9a00695efb3f7e816e17742d251559aff154b16d063a408bcd74d") + await nostr_client_test_disovery("99bb5591c9116600f845107d31f9b59e2f7c7e09a1ff802e84f1d43da557ca64", "3553867e9376c1611367b5ad0488d7d0b6bfc3fca2010282cc0dc4666da4e7fb") #await nostr_client_test_disovery_user("99bb5591c9116600f845107d31f9b59e2f7c7e09a1ff802e84f1d43da557ca64", # "58c52fdca7593dffea63ba6f758779d8251c6732f54e9dc0e56d7a1afe1bb1b6") # await nostr_client_test_censor_filter(wot) # await nostr_client_test_inactive_filter("99bb5591c9116600f845107d31f9b59e2f7c7e09a1ff802e84f1d43da557ca64") - await nostr_client_test_tts("Hello, this is a test. Mic check one, two.") + #await nostr_client_test_tts("Hello, this is a test. Mic check one, two.") # cashutoken = "cashuAeyJ0b2tlbiI6W3sicHJvb2ZzIjpbeyJpZCI6InZxc1VRSVorb0sxOSIsImFtb3VudCI6MSwiQyI6IjAyNWU3ODZhOGFkMmExYTg0N2YxMzNiNGRhM2VhMGIyYWRhZGFkOTRiYzA4M2E2NWJjYjFlOTgwYTE1NGIyMDA2NCIsInNlY3JldCI6InQ1WnphMTZKMGY4UElQZ2FKTEg4V3pPck5rUjhESWhGa291LzVzZFd4S0U9In0seyJpZCI6InZxc1VRSVorb0sxOSIsImFtb3VudCI6NCwiQyI6IjAyOTQxNmZmMTY2MzU5ZWY5ZDc3MDc2MGNjZmY0YzliNTMzMzVmZTA2ZGI5YjBiZDg2Njg5Y2ZiZTIzMjVhYWUwYiIsInNlY3JldCI6IlRPNHB5WE43WlZqaFRQbnBkQ1BldWhncm44UHdUdE5WRUNYWk9MTzZtQXM9In0seyJpZCI6InZxc1VRSVorb0sxOSIsImFtb3VudCI6MTYsIkMiOiIwMmRiZTA3ZjgwYmMzNzE0N2YyMDJkNTZiMGI3ZTIzZTdiNWNkYTBhNmI3Yjg3NDExZWYyOGRiZDg2NjAzNzBlMWIiLCJzZWNyZXQiOiJHYUNIdHhzeG9HM3J2WWNCc0N3V0YxbU1NVXczK0dDN1RKRnVwOHg1cURzPSJ9XSwibWludCI6Imh0dHBzOi8vbG5iaXRzLmJpdGNvaW5maXhlc3RoaXMub3JnL2Nhc2h1L2FwaS92MS9ScDlXZGdKZjlxck51a3M1eVQ2SG5rIn1dfQ==" # await nostr_client_test_image_private("a beautiful ostrich watching the sunset") diff --git a/tests/test_events.py b/tests/test_events.py index 3d80a40..154f087 100644 --- a/tests/test_events.py +++ b/tests/test_events.py @@ -1,4 +1,5 @@ import asyncio +import json from datetime import timedelta from pathlib import Path @@ -13,9 +14,7 @@ from nostr_dvm.utils.nip89_utils import NIP89Config from nostr_dvm.utils.nostr_utils import check_and_set_private_key - async def test(): - relay_list = dvmconfig.DVMConfig.RELAY_LIST keys = Keys.parse(check_and_set_private_key("test_client")) wait_for_send = False @@ -30,12 +29,12 @@ async def test(): await client.add_relay(relay) await client.connect() - await test_referred_events(client,"c70fbd4dbaad22c427d4359981d3bdddd3971ed1a38227ca2f8e5e760f58103c", - definitions.EventDefinitions.ANY_RESULT) + await test_referred_events(client, "c70fbd4dbaad22c427d4359981d3bdddd3971ed1a38227ca2f8e5e760f58103c", + definitions.EventDefinitions.ANY_RESULT) # shows kind 7000 reaction but not kind 6300 result (d05e7ae9271fe2d8968cccb67c01e3458dbafa4a415e306d49b22729b088c8a1) await test_referred_events(client, "5635e5dd930b3c831f6ab1e348bb488f3c9aca2f13190e93ab5e5e1e1ba1835e", - definitions.EventDefinitions.ANY_RESULT) + definitions.EventDefinitions.ANY_RESULT) bech32evnt = EventId.from_hex("5635e5dd930b3c831f6ab1e348bb488f3c9aca2f13190e93ab5e5e1e1ba1835e").to_bech32() print(bech32evnt) @@ -48,11 +47,12 @@ async def test(): print(nostruri) await test_search_by_user_since_days(client, - PublicKey.from_bech32("npub1nxa4tywfz9nqp7z9zp7nr7d4nchhclsf58lcqt5y782rmf2hefjquaa6q8"), 60, "Bitcoin") + PublicKey.from_bech32( + "npub1nxa4tywfz9nqp7z9zp7nr7d4nchhclsf58lcqt5y782rmf2hefjquaa6q8"), 60, + "Bitcoin") async def test_referred_events(client, event_id, kinds=None): - if kinds is None: kinds = [] @@ -72,9 +72,6 @@ async def test_referred_events(client, event_id, kinds=None): return None - - - async def test_gallery(): relay_list = dvmconfig.DVMConfig.RELAY_LIST keys = Keys.parse(check_and_set_private_key("test_client")) @@ -96,23 +93,47 @@ async def test_gallery(): tagname = "url" tags = [ - Tag.parse([tagname, "https://i.nostr.build/xEZqV.jpg", "3b0ec270394dc496f9f9c7db5c68a5b7f7311ff9080a51f1e8cb5f5cffc2c0b2", "wss://nostr.mom"]), - #Tag.parse([tagname, "https://i.nostr.build/2RnXd.jpg", "dd6e5c2891fbe9f53bcaa351b48faeeedccd16e9541b508adcb2c16d11bceaaf", "wss://nostr.mom"]), - #Tag.parse([tagname, "https://i.nostr.build/WG2Ra.jpg", "b2868e1ef93523ecf15b26e1cfdb6f252fe5074867d9c042fd6fcfbf07959193", "wss://nostr.mom"]), - #Tag.parse([tagname, "https://i.nostr.build/M5keE.jpg", "489402bf3ec070e7ebf2ba459508d2e1a408c0adad02954470602f232026a37d", "wss://nostr.mom"]), - Tag.parse([tagname, "https://v.nostr.build/M5kZ5.mp4", "0e37cb0373189e01be3c744c0434e0c8559953910e44b05ed270313c47abe142", "wss://nostr.mom"]), - Tag.parse([tagname, "https://i.nostr.build/vGLg7.jpg", "102d1f411a9a2b4de37ef62cdd4943673b4941080a51a8fa8829cd9f1de46d13", "wss://nostr.mom"]), - Tag.parse([tagname, "https://i.nostr.build/O4WxA.jpg", "4022d4e893c224186bbef4414340e35cbf251c681bc84ab05446fec1d2ec67df", "wss://nostr.mom"]), - Tag.parse([tagname, "https://i.nostr.build/M5a96.jpg", "6f04dc6a2a05f710b9c6c6d09a02c5fe0174da9c95399d3d01963a784d195803", "wss://nostr.mom"]), - Tag.parse([tagname, "https://i.nostr.build/WG02Y.jpg", "737a169c245ce7957a8b6acf190c57d70256cc52630862f5ba0fd7315ef83425", "wss://nostr.mom"]), - Tag.parse([tagname, "https://i.nostr.build/Dj2Q4.jpg", "c3a3a8759502cb3c06d592e5715cad0826982a2ff60a0ae525e3f253ab9e462a", "wss://nostr.mom"]), - #Tag.parse([tagname, "https://i.nostr.build/7G2G2.jpg", "015e71ded102e96d2b30f63dec0c04546d52a51f709709391af68d73f7502feb", "wss://nostr.mom"]), - #Tag.parse([tagname, "https://i.nostr.build/XVLkd.jpg", "43da37c84113d4c0bdc60ae1c82cef9761ff7a2a1ef29b1cc26abfd4932786c5", "wss://nostr.mom"]), - Tag.parse(["alt", "Profile Gallery List"]) - ] + Tag.parse([tagname, "https://i.nostr.build/xEZqV.jpg", + "3b0ec270394dc496f9f9c7db5c68a5b7f7311ff9080a51f1e8cb5f5cffc2c0b2", "wss://nostr.mom"]), + # Tag.parse([tagname, "https://i.nostr.build/2RnXd.jpg", "dd6e5c2891fbe9f53bcaa351b48faeeedccd16e9541b508adcb2c16d11bceaaf", "wss://nostr.mom"]), + # Tag.parse([tagname, "https://i.nostr.build/WG2Ra.jpg", "b2868e1ef93523ecf15b26e1cfdb6f252fe5074867d9c042fd6fcfbf07959193", "wss://nostr.mom"]), + # Tag.parse([tagname, "https://i.nostr.build/M5keE.jpg", "489402bf3ec070e7ebf2ba459508d2e1a408c0adad02954470602f232026a37d", "wss://nostr.mom"]), + Tag.parse([tagname, "https://v.nostr.build/M5kZ5.mp4", + "0e37cb0373189e01be3c744c0434e0c8559953910e44b05ed270313c47abe142", "wss://nostr.mom"]), + Tag.parse([tagname, "https://i.nostr.build/vGLg7.jpg", + "102d1f411a9a2b4de37ef62cdd4943673b4941080a51a8fa8829cd9f1de46d13", "wss://nostr.mom"]), + Tag.parse([tagname, "https://i.nostr.build/O4WxA.jpg", + "4022d4e893c224186bbef4414340e35cbf251c681bc84ab05446fec1d2ec67df", "wss://nostr.mom"]), + Tag.parse([tagname, "https://i.nostr.build/M5a96.jpg", + "6f04dc6a2a05f710b9c6c6d09a02c5fe0174da9c95399d3d01963a784d195803", "wss://nostr.mom"]), + Tag.parse([tagname, "https://i.nostr.build/Dj2Q4.jpg", + "737a169c245ce7957a8b6acf190c57d70256cc52630862f5ba0fd7315ef83425", "wss://nostr.mom"]), + Tag.parse([tagname, "https://i.nostr.build/Dj2Q4.jpg", + "c3a3a8759502cb3c06d592e5715cad0826982a2ff60a0ae525e3f253ab9e462a", "wss://nostr.mom"]), + # Tag.parse([tagname, "https://i.nostr.build/7G2G2.jpg", "015e71ded102e96d2b30f63dec0c04546d52a51f709709391af68d73f7502feb", "wss://nostr.mom"]), + # Tag.parse([tagname, "https://i.nostr.build/XVLkd.jpg", "43da37c84113d4c0bdc60ae1c82cef9761ff7a2a1ef29b1cc26abfd4932786c5", "wss://nostr.mom"]), + Tag.parse(["alt", "Profile Gallery List"]) + ] + keyhex = "27da5b78f4b1d1c33817f76cf4c40b733e99cd192585ea1b711142682c3594b9" + keys = Keys.parse(keyhex) + draft = { + + "content": "Hello", + "kind": 1, + "pubkey": keys.public_key().to_hex(), # 48h since gmt, + "tags": [], + "createdAt": 16123123} + + event = EventBuilder.text_note("Hello", []).custom_created_at(Timestamp.from_secs(1720464386)).to_event(keys) + + print(event.as_json()) + # await gallery_announce_list(tags, dvm_config, client) + + #evt = EventBuilder.delete([EventId.parse("40e7a72f10d9a6511dab897b3b4a94f7eff04f509886de95de3897d06ca9a92c")], + # "deleted").to_event(keys) + #await client.send_event(evt) - await gallery_announce_list(tags, dvm_config, client) async def test_search_by_user_since_days(client, pubkey, days, prompt): since_seconds = int(days) * 24 * 60 * 60 @@ -131,7 +152,6 @@ async def test_search_by_user_since_days(client, pubkey, days, prompt): return None - if __name__ == '__main__': env_path = Path('.env') if env_path.is_file(): @@ -143,4 +163,3 @@ if __name__ == '__main__': asyncio.run(test_gallery()) # works -