From 0ad44f2917d4c3d262b2ba7e81444377df353a52 Mon Sep 17 00:00:00 2001 From: Believethehype <1097224+believethehype@users.noreply.github.com> Date: Sat, 1 Jun 2024 23:46:00 +0200 Subject: [PATCH] nip89 announce relays, revert some changes to content dvms --- .../content_discovery_currently_popular.py | 102 +++++------ ...discovery_currently_popular_by_top_zaps.py | 29 ++-- ...t_discovery_currently_popular_followers.py | 113 ++++++------ ...ntent_discovery_currently_popular_topic.py | 164 ++++++++++-------- setup.py | 2 +- tests/discovery.py | 9 +- 6 files changed, 221 insertions(+), 198 deletions(-) diff --git a/nostr_dvm/tasks/content_discovery_currently_popular.py b/nostr_dvm/tasks/content_discovery_currently_popular.py index 524ba06..11a98ea 100644 --- a/nostr_dvm/tasks/content_discovery_currently_popular.py +++ b/nostr_dvm/tasks/content_discovery_currently_popular.py @@ -33,7 +33,6 @@ class DicoverContentCurrentlyPopular(DVMTaskInterface): min_reactions = 2 personalized = False result = "" - logger = False def __init__(self, name, dvm_config: DVMConfig, nip89config: NIP89Config, nip88config: NIP88Config = None, admin_config: AdminConfig = None, options=None): @@ -48,32 +47,16 @@ class DicoverContentCurrentlyPopular(DVMTaskInterface): self.request_form['options'] = json.dumps(opts) self.last_schedule = Timestamp.now().as_secs() - if self.options is not None: - 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")) - if self.options.get("logger"): - self.logger = bool(self.options.get("logger")) - if self.logger: - init_logger(LogLevel.DEBUG) - - 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 = NostrDatabase.sqlite(self.db_name) - self.client = ClientBuilder().signer(signer).database(database).opts(opts).build() - - ropts = RelayOptions().ping(False) - self.client.add_relay_with_opts("wss://relay.damus.io", ropts) - self.client.add_relay_with_opts("wss://nostr.oxtr.dev", ropts) - self.client.add_relay_with_opts("wss://nostr21.com", ropts) - - self.client.connect() + 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: self.sync_db() @@ -97,7 +80,7 @@ class DicoverContentCurrentlyPopular(DVMTaskInterface): # default values search = "" - max_results = 100 + max_results = 200 for tag in event.tags(): if tag.as_vec()[0] == 'i': @@ -128,32 +111,45 @@ class DicoverContentCurrentlyPopular(DVMTaskInterface): options = self.set_options(request_form) + opts = (Options().wait_for_send(False).send_timeout(timedelta(seconds=self.dvm_config.RELAY_TIMEOUT))) + sk = SecretKey.from_hex(self.dvm_config.PRIVATE_KEY) + keys = Keys.parse(sk.to_hex()) + signer = NostrSigner.keys(keys) + + database = NostrDatabase.sqlite(self.db_name) + cli = ClientBuilder().database(database).signer(signer).opts(opts).build() + cli.connect() + + # Negentropy reconciliation + # Query events from database timestamp_hour_ago = Timestamp.now().as_secs() - self.db_since since = Timestamp.from_secs(timestamp_hour_ago) filter1 = Filter().kind(definitions.EventDefinitions.KIND_NOTE).since(since) - events = self.client.database().query([filter1]) + events = cli.database().query([filter1]) print("[" + self.dvm_config.NIP89.NAME + "] Considering " + str(len(events)) + " Events") - ns.finallist = {} for event in events: if event.created_at().as_secs() > timestamp_hour_ago: filt = Filter().kinds([definitions.EventDefinitions.KIND_ZAP, definitions.EventDefinitions.KIND_REPOST, definitions.EventDefinitions.KIND_REACTION, definitions.EventDefinitions.KIND_NOTE]).event(event.id()).since(since) - reactions = self.client.database().query([filt]) + reactions = cli.database().query([filt]) if len(reactions) >= self.min_reactions: ns.finallist[event.id().to_hex()] = len(reactions) - if len(ns.finallist) == 0: + cli.disconnect() + cli.shutdown() return self.result 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()) - + cli.disconnect() + cli.shutdown() return json.dumps(result_list) def post_process(self, result, event): @@ -175,14 +171,22 @@ class DicoverContentCurrentlyPopular(DVMTaskInterface): if self.dvm_config.UPDATE_DATABASE: self.sync_db() self.last_schedule = Timestamp.now().as_secs() - if not self.personalized: - try: - self.result = self.calculate_result(self.request_form) - except Exception as e: - print("EXCEPTION: " + str(e)) + self.result = self.calculate_result(self.request_form) return 1 def sync_db(self): + opts = (Options().wait_for_send(False).send_timeout(timedelta(seconds=self.dvm_config.RELAY_TIMEOUT))) + sk = SecretKey.from_hex(self.dvm_config.PRIVATE_KEY) + keys = Keys.parse(sk.to_hex()) + signer = NostrSigner.keys(keys) + database = NostrDatabase.sqlite(self.db_name) + cli = ClientBuilder().signer(signer).database(database).opts(opts).build() + + ropts = RelayOptions().ping(True) + cli.add_relay_with_opts("wss://relay.damus.io", ropts) + cli.add_relay_with_opts("wss://nostr.oxtr.dev", ropts) + cli.add_relay_with_opts("wss://nostr21.com", ropts) + cli.connect() timestamp_hour_ago = Timestamp.now().as_secs() - self.db_since lasthour = Timestamp.from_secs(timestamp_hour_ago) @@ -191,22 +195,21 @@ class DicoverContentCurrentlyPopular(DVMTaskInterface): definitions.EventDefinitions.KIND_ZAP]).since(lasthour) # Notes, reactions, zaps # filter = Filter().author(keys.public_key()) - print("[" + self.dvm_config.NIP89.NAME + "] Syncing notes of the last " + str( + print("[" + self.dvm_config.IDENTIFIER + "] Syncing notes of the last " + str( self.db_since) + " seconds.. this might take a while..") dbopts = NegentropyOptions().direction(NegentropyDirection.DOWN) - self.client.reconcile(filter1, dbopts) - filter_delete = Filter().until(Timestamp.from_secs(Timestamp.now().as_secs() - self.db_since)) - self.client.database().delete(filter_delete) # Clear old events so db doesn't get too full. + cli.reconcile(filter1, dbopts) + database.delete(Filter().until(Timestamp.from_secs( + Timestamp.now().as_secs() - self.db_since))) # Clear old events so db doesnt get too full. print( - "[" + self.dvm_config.NIP89.NAME + "] Done Syncing Notes of the last " + str(self.db_since) + " seconds..") + "[" + self.dvm_config.IDENTIFIER + "] 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, cost=0, update_rate=180, processing_msg=None, - update_db=True): +def build_example(name, identifier, admin_config, options, cost=0, update_rate=180, processing_msg=None, update_db=True): dvm_config = build_default_config(identifier) dvm_config.USE_OWN_VENV = False dvm_config.SHOWLOG = True @@ -245,15 +248,14 @@ def build_example(name, identifier, admin_config, options, cost=0, update_rate=1 nip89config.DTAG = check_and_set_d_tag(identifier, name, dvm_config.PRIVATE_KEY, nip89info["image"]) nip89config.CONTENT = json.dumps(nip89info) - # admin_config.UPDATE_PROFILE = False - # admin_config.REBROADCAST_NIP89 = False + #admin_config.UPDATE_PROFILE = False + #admin_config.REBROADCAST_NIP89 = False return DicoverContentCurrentlyPopular(name=name, dvm_config=dvm_config, nip89config=nip89config, admin_config=admin_config, options=options) -def build_example_subscription(name, identifier, admin_config, options, update_rate=180, processing_msg=None, - update_db=True): +def build_example_subscription(name, identifier, admin_config, options, update_rate=180, processing_msg=None, update_db=True): dvm_config = build_default_config(identifier) dvm_config.USE_OWN_VENV = False dvm_config.SHOWLOG = True @@ -303,9 +305,9 @@ def build_example_subscription(name, identifier, admin_config, options, update_r nip88config.PERK2DESC = "Support NostrDVM & NostrSDK development" nip88config.PAYMENT_VERIFIER_PUBKEY = "5b5c045ecdf66fb540bdf2049fe0ef7f1a566fa427a4fe50d400a011b65a3a7e" - # admin_config.UPDATE_PROFILE = False - # admin_config.REBROADCAST_NIP89 = False - # admin_config.REBROADCAST_NIP88 = False + #admin_config.UPDATE_PROFILE = False + #admin_config.REBROADCAST_NIP89 = False + #admin_config.REBROADCAST_NIP88 = False # admin_config.FETCH_NIP88 = True # admin_config.EVENTID = "" @@ -317,4 +319,4 @@ def build_example_subscription(name, identifier, admin_config, options, update_r if __name__ == '__main__': - process_venv(DicoverContentCurrentlyPopular) + process_venv(DicoverContentCurrentlyPopular) \ No newline at end of file diff --git a/nostr_dvm/tasks/content_discovery_currently_popular_by_top_zaps.py b/nostr_dvm/tasks/content_discovery_currently_popular_by_top_zaps.py index a514d36..447e108 100644 --- a/nostr_dvm/tasks/content_discovery_currently_popular_by_top_zaps.py +++ b/nostr_dvm/tasks/content_discovery_currently_popular_by_top_zaps.py @@ -60,19 +60,6 @@ class DicoverContentCurrentlyPopularZaps(DVMTaskInterface): if self.logger: init_logger(LogLevel.DEBUG) - 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 = NostrDatabase.sqlite(self.db_name) - self.client = ClientBuilder().signer(signer).database(database).opts(opts).build() - - ropts = RelayOptions().ping(False) - self.client.add_relay_with_opts("wss://relay.damus.io", ropts) - self.client.add_relay_with_opts("wss://nostr.oxtr.dev", ropts) - self.client.add_relay_with_opts("wss://nostr21.com", ropts) - - self.client.connect() if self.dvm_config.UPDATE_DATABASE: self.sync_db() @@ -126,6 +113,15 @@ class DicoverContentCurrentlyPopularZaps(DVMTaskInterface): options = self.set_options(request_form) + opts = (Options().wait_for_send(False).send_timeout(timedelta(seconds=self.dvm_config.RELAY_TIMEOUT))) + sk = SecretKey.from_hex(self.dvm_config.PRIVATE_KEY) + keys = Keys.parse(sk.to_hex()) + signer = NostrSigner.keys(keys) + + database = NostrDatabase.sqlite(self.db_name) + cli = ClientBuilder().database(database).signer(signer).opts(opts).build() + + cli.connect() # Negentropy reconciliation # Query events from database @@ -133,14 +129,14 @@ class DicoverContentCurrentlyPopularZaps(DVMTaskInterface): since = Timestamp.from_secs(timestamp_hour_ago) filter1 = Filter().kind(definitions.EventDefinitions.KIND_NOTE).since(since) - events = self.client.database().query([filter1]) + events = cli.database().query([filter1]) print("[" + self.dvm_config.NIP89.NAME + "] Considering " + str(len(events)) + " Events") ns.finallist = {} for event in events: if event.created_at().as_secs() > timestamp_hour_ago: filt = Filter().kinds([definitions.EventDefinitions.KIND_ZAP]).event(event.id()).since(since) - reactions = self.client.database().query([filt]) + reactions = cli.database().query([filt]) invoice_amount = 0 haspreimage = False if len(reactions) >= self.min_reactions: @@ -165,6 +161,9 @@ class DicoverContentCurrentlyPopularZaps(DVMTaskInterface): e_tag = Tag.parse(["e", entry[0]]) result_list.append(e_tag.as_vec()) + cli.disconnect() + cli.shutdown() + return json.dumps(result_list) def post_process(self, result, event): diff --git a/nostr_dvm/tasks/content_discovery_currently_popular_followers.py b/nostr_dvm/tasks/content_discovery_currently_popular_followers.py index 83270e7..871c626 100644 --- a/nostr_dvm/tasks/content_discovery_currently_popular_followers.py +++ b/nostr_dvm/tasks/content_discovery_currently_popular_followers.py @@ -31,7 +31,6 @@ class DicoverContentCurrentlyPopularFollowers(DVMTaskInterface): db_since = 2 * 3600 db_name = "db/nostr_recent_notes2.db" min_reactions = 2 - logger = False def __init__(self, name, dvm_config: DVMConfig, nip89config: NIP89Config, nip88config: NIP88Config = None, admin_config: AdminConfig = None, options=None): @@ -40,33 +39,15 @@ class DicoverContentCurrentlyPopularFollowers(DVMTaskInterface): admin_config=admin_config, options=options) self.last_schedule = Timestamp.now().as_secs() - if self.options is not None: - 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")) - if self.options.get("logger"): - self.logger = bool(self.options.get("logger")) - if self.logger: - init_logger(LogLevel.DEBUG) + 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")) - opts = (Options().wait_for_send(False).send_timeout(timedelta(seconds=self.dvm_config.RELAY_TIMEOUT))) - sk = SecretKey.from_hex(self.dvm_config.PRIVATE_KEY) - keys = Keys.parse(sk.to_hex()) - signer = NostrSigner.keys(keys) - database = NostrDatabase.sqlite(self.db_name) - self.client = ClientBuilder().signer(signer).database(database).opts(opts).build() - - ropts = RelayOptions().ping(False) - self.client.add_relay_with_opts("wss://relay.damus.io", ropts) - self.client.add_relay_with_opts("wss://nostr.oxtr.dev", ropts) - self.client.add_relay_with_opts("wss://nostr21.com", ropts) - - #ropts = RelayOptions().ping(False) - #self.client.add_relay_with_opts("wss://nostr.band", ropts) - - self.client.connect() + use_logger = False + if use_logger: + init_logger(LogLevel.DEBUG) if self.dvm_config.UPDATE_DATABASE: self.sync_db() @@ -89,6 +70,7 @@ class DicoverContentCurrentlyPopularFollowers(DVMTaskInterface): user = event.author().to_hex() max_results = 100 + for tag in event.tags(): if tag.as_vec()[0] == 'i': input_type = tag.as_vec()[2] @@ -99,6 +81,8 @@ class DicoverContentCurrentlyPopularFollowers(DVMTaskInterface): elif param == "user": # check for param type user = tag.as_vec()[2] + + options = { "max_results": max_results, "user": user, @@ -112,21 +96,34 @@ class DicoverContentCurrentlyPopularFollowers(DVMTaskInterface): 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_LONG_TIMEOUT)).relay_limits( - relaylimits)) + 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 = NostrDatabase.sqlite(self.db_name) + cli = ClientBuilder().database(database).signer(signer).opts(opts).build() + cli.add_relay("wss://relay.damus.io") + cli.add_relay("wss://nostr.oxtr.dev") + cli.add_relay("wss://nostr.mom") + + #ropts = RelayOptions().ping(False) + #cli.add_relay_with_opts("wss://nostr.band", ropts) + + cli.connect() user = PublicKey.parse(options["user"]) followers_filter = Filter().author(user).kinds([Kind(3)]) - followers = self.client.get_events_of([followers_filter], timedelta(seconds=self.dvm_config.RELAY_TIMEOUT)) + followers = cli.get_events_of([followers_filter], timedelta(seconds=self.dvm_config.RELAY_TIMEOUT)) + #print(followers) # Negentropy reconciliation # Query events from database timestamp_since = Timestamp.now().as_secs() - self.db_since since = Timestamp.from_secs(timestamp_since) + result_list = [] if len(followers) > 0: @@ -137,32 +134,36 @@ class DicoverContentCurrentlyPopularFollowers(DVMTaskInterface): newest = entry.created_at().as_secs() best_entry = entry - # print(best_entry.as_json()) + #print(best_entry.as_json()) followings = [] for tag in best_entry.tags(): if tag.as_vec()[0] == "p": following = PublicKey.parse(tag.as_vec()[1]) followings.append(following) - print("[" + self.dvm_config.NIP89.NAME + "] Considering " + str(len(followings)) + " Followers") + filter1 = Filter().kind(definitions.EventDefinitions.KIND_NOTE).authors(followings).since(since) - events = self.client.database().query([filter1]) + events = cli.database().query([filter1]) print("[" + self.dvm_config.NIP89.NAME + "] Considering " + str(len(events)) + " Events") ns.finallist = {} for event in events: - # if event.created_at().as_secs() > timestamp_since: + #if event.created_at().as_secs() > timestamp_since: filt = Filter().kinds( - [EventDefinitions.KIND_ZAP, EventDefinitions.KIND_REACTION, EventDefinitions.KIND_REPOST, - EventDefinitions.KIND_NOTE]).event(event.id()).since(since) - reactions = self.client.database().query([filt]) + [definitions.EventDefinitions.KIND_ZAP, definitions.EventDefinitions.KIND_REACTION, definitions.EventDefinitions.KIND_REPOST, + definitions.EventDefinitions.KIND_NOTE]).event(event.id()).since(since) + reactions = cli.database().query([filt]) if len(reactions) >= self.min_reactions: ns.finallist[event.id().to_hex()] = len(reactions) - finallist_sorted = sorted(ns.finallist.items(), key=lambda x: x[1], reverse=True)[ - :int(options["max_results"])] + + + 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()) + cli.connect() + cli.shutdown() return json.dumps(result_list) @@ -187,34 +188,39 @@ class DicoverContentCurrentlyPopularFollowers(DVMTaskInterface): if self.dvm_config.UPDATE_DATABASE: self.sync_db() self.last_schedule = Timestamp.now().as_secs() - return 1 def sync_db(self): + opts = (Options().wait_for_send(False).send_timeout(timedelta(seconds=self.dvm_config.RELAY_TIMEOUT))) + sk = SecretKey.from_hex(self.dvm_config.PRIVATE_KEY) + keys = Keys.parse(sk.to_hex()) + signer = NostrSigner.keys(keys) + database = NostrDatabase.sqlite(self.db_name) + cli = ClientBuilder().signer(signer).database(database).opts(opts).build() + cli.add_relay("wss://relay.damus.io") + cli.connect() timestamp_hour_ago = Timestamp.now().as_secs() - self.db_since lasthour = Timestamp.from_secs(timestamp_hour_ago) filter1 = Filter().kinds([definitions.EventDefinitions.KIND_NOTE, definitions.EventDefinitions.KIND_REACTION, - definitions.EventDefinitions.KIND_ZAP, definitions.EventDefinitions.KIND_REPOST]).since(lasthour) # Notes, reactions, zaps + definitions.EventDefinitions.KIND_ZAP]).since(lasthour) # Notes, reactions, zaps # filter = Filter().author(keys.public_key()) - print("[" + self.dvm_config.NIP89.NAME + "] Syncing notes of the last " + str( - self.db_since) + " seconds.. this might take a while..") + print("[" + self.dvm_config.IDENTIFIER + "] Syncing notes of the last " + str(self.db_since) + " seconds.. this might take a while..") dbopts = NegentropyOptions().direction(NegentropyDirection.DOWN) - self.client.reconcile(filter1, dbopts) - filter_delete = Filter().until(Timestamp.from_secs(Timestamp.now().as_secs() - self.db_since)) - self.client.database().delete(filter_delete) # Clear old events so db doesn't get too full. - print( - "[" + self.dvm_config.NIP89.NAME + "] Done Syncing Notes of the last " + str(self.db_since) + " seconds..") + cli.reconcile(filter1, dbopts) + database.delete(Filter().until(Timestamp.from_secs( + Timestamp.now().as_secs() - self.db_since))) # Clear old events so db doesnt get too full. + + print("[" + self.dvm_config.IDENTIFIER + "] 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, cost=0, update_rate=300, processing_msg=None, - update_db=True): +def build_example(name, identifier, admin_config, options, 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 @@ -255,8 +261,7 @@ def build_example(name, identifier, admin_config, options, cost=0, update_rate=3 # admin_config.UPDATE_PROFILE = False # admin_config.REBROADCAST_NIP89 = False - return DicoverContentCurrentlyPopularFollowers(name=name, dvm_config=dvm_config, nip89config=nip89config, - options=options, + return DicoverContentCurrentlyPopularFollowers(name=name, dvm_config=dvm_config, nip89config=nip89config, options=options, admin_config=admin_config) @@ -319,4 +324,4 @@ def build_example_subscription(name, identifier, admin_config, options, processi if __name__ == '__main__': - process_venv(DicoverContentCurrentlyPopularFollowers) + process_venv(DicoverContentCurrentlyPopularFollowers) \ No newline at end of file diff --git a/nostr_dvm/tasks/content_discovery_currently_popular_topic.py b/nostr_dvm/tasks/content_discovery_currently_popular_topic.py index 969de9c..01ac9eb 100644 --- a/nostr_dvm/tasks/content_discovery_currently_popular_topic.py +++ b/nostr_dvm/tasks/content_discovery_currently_popular_topic.py @@ -2,8 +2,7 @@ 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, RelayOptions + ClientBuilder, Filter, NegentropyOptions, NegentropyDirection, init_logger, LogLevel, Event, EventId, Kind from nostr_dvm.interfaces.dvmtaskinterface import DVMTaskInterface, process_venv from nostr_dvm.utils import definitions @@ -15,7 +14,7 @@ from nostr_dvm.utils.nip89_utils import NIP89Config, check_and_set_d_tag, create from nostr_dvm.utils.output_utils import post_process_list_to_events """ -This File contains a Module to discover popular notes by topic +This File contains a Module to discover popular notes by topics Accepted Inputs: none Outputs: A list of events Params: None @@ -29,18 +28,18 @@ class DicoverContentCurrentlyPopularbyTopic(DVMTaskInterface): dvm_config: DVMConfig last_schedule: int min_reactions = 2 - db_since = 10 * 3600 + db_since = 10*3600 db_name = "db/nostr_default_recent_notes.db" search_list = [] avoid_list = [] must_list = [] personalized = False result = "" - logger = False def __init__(self, name, dvm_config: DVMConfig, nip89config: NIP89Config, nip88config: NIP88Config = None, admin_config: AdminConfig = None, options=None): + super().__init__(name=name, dvm_config=dvm_config, nip89config=nip89config, nip88config=nip88config, admin_config=admin_config, options=options) @@ -53,45 +52,26 @@ class DicoverContentCurrentlyPopularbyTopic(DVMTaskInterface): self.request_form['options'] = json.dumps(opts) dvm_config.SCRIPT = os.path.abspath(__file__) - if self.options is not None: - 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")) - if self.options.get("logger"): - self.logger = bool(self.options.get("logger")) - if self.logger: - init_logger(LogLevel.DEBUG) + 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")) - relaylimits = RelayLimits.disable() - opts = (Options().wait_for_send(True).send_timeout(timedelta(seconds=dvm_config.RELAY_LONG_TIMEOUT)) - .relay_limits(relaylimits)) - sk = SecretKey.from_hex(self.dvm_config.PRIVATE_KEY) - keys = Keys.parse(sk.to_hex()) - signer = NostrSigner.keys(keys) - database = NostrDatabase.sqlite(self.db_name) - self.client = ClientBuilder().signer(signer).database(database).opts(opts).build() - #self.client.add_relay("wss://relay.damus.io") - #self.client.add_relay("wss://nostr.oxtr.dev") - - ropts = RelayOptions().ping(False) - self.client.add_relay_with_opts("wss://relay.damus.io", ropts) - self.client.add_relay_with_opts("wss://nostr.oxtr.dev", ropts) - self.client.add_relay_with_opts("wss://nostr21.com", ropts) - - self.client.connect() + use_logger = False + if use_logger: + init_logger(LogLevel.DEBUG) if self.dvm_config.UPDATE_DATABASE: self.sync_db() @@ -109,6 +89,7 @@ class DicoverContentCurrentlyPopularbyTopic(DVMTaskInterface): 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()} # default values @@ -133,10 +114,11 @@ class DicoverContentCurrentlyPopularbyTopic(DVMTaskInterface): # if the dvm supports individual results, recalculate it every time for the request if self.personalized: return self.calculate_result(request_form) - # else return the result that gets updated once every schenduled update. In this case on database update. + #else return the result that gets updated once every schenduled update. In this case on database update. else: return self.result + def post_process(self, result, event): """Overwrite the interface function to return a social client readable format, if requested""" for tag in event.tags(): @@ -147,7 +129,6 @@ class DicoverContentCurrentlyPopularbyTopic(DVMTaskInterface): # if not text/plain, don't post-process return result - def calculate_result(self, request_form): from nostr_sdk import Filter from types import SimpleNamespace @@ -155,16 +136,26 @@ class DicoverContentCurrentlyPopularbyTopic(DVMTaskInterface): options = self.set_options(request_form) + opts = (Options().wait_for_send(False).send_timeout(timedelta(seconds=self.dvm_config.RELAY_TIMEOUT))) + sk = SecretKey.from_hex(self.dvm_config.PRIVATE_KEY) + keys = Keys.parse(sk.to_hex()) + signer = NostrSigner.keys(keys) + database = NostrDatabase.sqlite(self.db_name) + cli = ClientBuilder().database(database).signer(signer).opts(opts).build() + + cli.connect() + + # Negentropy reconciliation + # Query events from database 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 = self.client.database().query([filter1]) + events = cli.database().query([filter1]) print("[" + self.dvm_config.NIP89.NAME + "] Considering " + str(len(events)) + " Events") - - ns.final_list = {} + ns.finallist = {} for event in events: if all(ele in event.content().lower() for ele in self.must_list): @@ -175,61 +166,75 @@ class DicoverContentCurrentlyPopularbyTopic(DVMTaskInterface): [definitions.EventDefinitions.KIND_ZAP, definitions.EventDefinitions.KIND_REACTION, definitions.EventDefinitions.KIND_REPOST, definitions.EventDefinitions.KIND_NOTE]).event(event.id()).since(since) - reactions = self.client.database().query([filt]) + reactions = cli.database().query([filt]) if len(reactions) >= self.min_reactions: - ns.final_list[event.id().to_hex()] = len(reactions) + ns.finallist[event.id().to_hex()] = len(reactions) result_list = [] - finallist_sorted = sorted(ns.final_list.items(), key=lambda x: x[1], reverse=True)[:int(options["max_results"])] + 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()) + print(len(result_list)) + cli.disconnect() + cli.shutdown() return json.dumps(result_list) + 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: - try: - if self.dvm_config.UPDATE_DATABASE: - self.sync_db() - self.last_schedule = Timestamp.now().as_secs() - if not self.personalized: - self.result = self.calculate_result(self.request_form) - except Exception as e: - print(e) + if self.dvm_config.UPDATE_DATABASE: + self.sync_db() + self.last_schedule = Timestamp.now().as_secs() + self.result = self.calculate_result(self.request_form) + #print(self.result) return 1 def sync_db(self): + opts = (Options().wait_for_send(False).send_timeout(timedelta(seconds=self.dvm_config.RELAY_TIMEOUT))) + sk = SecretKey.from_hex(self.dvm_config.PRIVATE_KEY) + keys = Keys.parse(sk.to_hex()) + signer = NostrSigner.keys(keys) + database = NostrDatabase.sqlite(self.db_name) + cli = ClientBuilder().signer(signer).database(database).opts(opts).build() + cli.add_relay("wss://relay.damus.io") + cli.add_relay("wss://nostr.oxtr.dev") + cli.add_relay("wss://relay.nostr.net") + cli.add_relay("wss://relay.nostr.bg") + cli.add_relay("wss://nostr.wine") + cli.add_relay("wss://nostr21.com") + + #RELAY_LIST = [ "wss://nostr.wine", + # , "wss://relay.nostr.bg", + # , "wss://relay.nostr.net" + # ] + cli.connect() timestamp_since = Timestamp.now().as_secs() - self.db_since since = Timestamp.from_secs(timestamp_since) - filter1 = Filter().kinds([EventDefinitions.KIND_NOTE, EventDefinitions.KIND_REACTION, EventDefinitions.KIND_ZAP, - definitions.EventDefinitions.KIND_REPOST - ]).since(since) # Notes, reactions, zaps + 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()) - print("[" + self.dvm_config.NIP89.NAME + "] Syncing notes of the last " + str( - self.db_since) + " seconds.. this might take a while..") + print("[" + self.dvm_config.IDENTIFIER + "] Syncing notes of the last " + str(self.db_since) + " seconds.. this might take a while..") dbopts = NegentropyOptions().direction(NegentropyDirection.DOWN) - self.client.reconcile(filter1, dbopts) - filter_delete = Filter().until(Timestamp.from_secs(Timestamp.now().as_secs() - self.db_since)) - self.client.database().delete(filter_delete) # Clear old events so db doesn't get too full. + cli.reconcile(filter1, dbopts) + database.delete(Filter().until(Timestamp.from_secs( + Timestamp.now().as_secs() - self.db_since))) # Clear old events so db doesn't get too full. - print( - "[" + self.dvm_config.NIP89.NAME + "] Done Syncing Notes of the last " + str(self.db_since) + " seconds..") + print("[" + self.dvm_config.IDENTIFIER + "] 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): +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 @@ -242,6 +247,7 @@ def build_example(name, identifier, admin_config, options, image, description, u dvm_config.CUSTOM_PROCESSING_MESSAGE = processing_msg admin_config.LUD16 = dvm_config.LN_ADDRESS + # Add NIP89 nip89info = { "name": name, @@ -267,11 +273,10 @@ def build_example(name, identifier, admin_config, options, image, description, u nip89config.CONTENT = json.dumps(nip89info) return DicoverContentCurrentlyPopularbyTopic(name=name, dvm_config=dvm_config, nip89config=nip89config, - admin_config=admin_config, options=options) + admin_config=admin_config, options=options) -def build_example_subscription(name, identifier, admin_config, options, image, description, processing_msg=None, - update_db=True): +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 @@ -282,6 +287,7 @@ def build_example_subscription(name, identifier, admin_config, options, image, d dvm_config.CUSTOM_PROCESSING_MESSAGE = processing_msg admin_config.LUD16 = dvm_config.LN_ADDRESS + # Add NIP89 nip89info = { "name": name, @@ -319,11 +325,17 @@ def build_example_subscription(name, identifier, admin_config, options, image, d 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 DicoverContentCurrentlyPopularbyTopic(name=name, dvm_config=dvm_config, nip89config=nip89config, - nip88config=nip88config, - admin_config=admin_config, - options=options) + nip88config=nip88config, + admin_config=admin_config, + options=options) if __name__ == '__main__': - process_venv(DicoverContentCurrentlyPopularbyTopic) + process_venv(DicoverContentCurrentlyPopularbyTopic) \ No newline at end of file diff --git a/setup.py b/setup.py index caf0699..eb77865 100644 --- a/setup.py +++ b/setup.py @@ -1,6 +1,6 @@ from setuptools import setup, find_packages -VERSION = '0.5.5' +VERSION = '0.5.6' 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 124e986..270a343 100644 --- a/tests/discovery.py +++ b/tests/discovery.py @@ -19,7 +19,7 @@ from nostr_dvm.utils.nostr_utils import check_and_set_private_key from nostr_dvm.utils.zap_utils import check_and_set_ln_bits_keys rebbroadcast_NIP89 = False # Announce NIP89 on startup -global_update_rate = 300 # set this high on first sync so db can fully sync before another process trys to. +global_update_rate = 120 # set this high on first sync so db can fully sync before another process trys to. use_logger = True #git_hash = NostrLibrary().git_hash_version() @@ -46,6 +46,7 @@ def build_example_nostrband(name, identifier, admin_config, image, about, custom "amount": "Free", "encryptionSupported": True, "cashuAccepted": True, + "relays": dvm_config.RELAY_LIST, "nip90Params": {} } nip89config = NIP89Config() @@ -81,6 +82,7 @@ def build_example_topic(name, identifier, admin_config, options, image, descript "encryptionSupported": True, "cashuAccepted": True, "personalized": False, + "relays": dvm_config.RELAY_LIST, "amount": create_amount_tag(cost), "nip90Params": { "max_results": { @@ -126,6 +128,7 @@ def build_example_popular(name, identifier, admin_config, options, image, cost=0 "encryptionSupported": True, "cashuAccepted": True, "personalized": False, + "relays": dvm_config.RELAY_LIST, "amount": create_amount_tag(cost), "nip90Params": { "max_results": { @@ -168,6 +171,7 @@ def build_example_popular_followers(name, identifier, admin_config, options, ima "encryptionSupported": True, "cashuAccepted": True, "personalized": True, + "relays": dvm_config.RELAY_LIST, "amount": create_amount_tag(cost), "nip90Params": { "max_results": { @@ -213,6 +217,7 @@ def build_example_top_zapped(name, identifier, admin_config, options, image, cos "encryptionSupported": True, "cashuAccepted": True, "personalized": False, + "relays": dvm_config.RELAY_LIST, "amount": create_amount_tag(cost), "nip90Params": { "max_results": { @@ -373,7 +378,7 @@ def playground(): options_top_zapped = { "db_name": "db/nostr_recent_notes.db", - "db_since": 60 * 60 * 4, # 4h since gmt, + "db_since": 60 * 60 * 6, # 6h since gmt, } cost = 0 image = "https://image.nostr.build/c6879f458252641d04d0aa65fd7f1e005a4f7362fd407467306edc2f4acdb113.jpg"