nineteen_ninetynine 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 6c5aed33e8c56b694e833f420ec1bdd7785ab715873ded1f97f8a4d1595dd976
4
+ data.tar.gz: c11198f5a0bd7992a64e363f034445dd4139c8a119ea8634a5fadf2fadde47f9
5
+ SHA512:
6
+ metadata.gz: 718255d94b08fe308f1297e90d129fc6a4cd2480629fc46c3d62b31ac7c79c75758ad83fcb102bf778f4eeb83ecd324e97efbbf0a7463e20d5e9416168cf9a90
7
+ data.tar.gz: 42cdaf0db130b93cde2b9c5aa6cbee2c15781e2b65b915a9967ef2decddd700c83f0380555b99da0ea76bc432f395289baad914459ad6f8f9897a32f77b381d7
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,14 @@
1
+ inherit_from: "https://raw.githubusercontent.com/cookpad/styleguide/master/.rubocop.yml"
2
+ AllCops:
3
+ TargetRubyVersion: 2.6
4
+
5
+ Style/StringLiterals:
6
+ Enabled: true
7
+ EnforcedStyle: double_quotes
8
+
9
+ Style/StringLiteralsInInterpolation:
10
+ Enabled: true
11
+ EnforcedStyle: double_quotes
12
+
13
+ Layout/LineLength:
14
+ Max: 120
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-05-30
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at asonas@cookpad.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in nineteen_ninetynine.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "rubocop", "~> 1.21"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Yuya Fujiwara
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # NineteenNinetynine
2
+
3
+ TODO: Delete this and the text below, and describe your gem
4
+
5
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/nineteen_ninetynine`. To experiment with that code, run `bin/console` for an interactive prompt.
6
+
7
+ ## Installation
8
+
9
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ $ bundle add UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
14
+
15
+ If bundler is not being used to manage dependencies, install the gem by executing:
16
+
17
+ $ gem install UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
18
+
19
+ ## Usage
20
+
21
+ TODO: Write usage instructions here
22
+
23
+ ## Development
24
+
25
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
26
+
27
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
28
+
29
+ ## Contributing
30
+
31
+ Bug reports and pull requests are welcome on GitHub at https://github.com/asonas/nineteen_ninetynine. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/asonas/nineteen_ninetynine/blob/master/CODE_OF_CONDUCT.md).
32
+
33
+ ## License
34
+
35
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
36
+
37
+ ## Code of Conduct
38
+
39
+ Everyone interacting in the NineteenNinetynine project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/asonas/nineteen_ninetynine/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env ruby
2
+ require "nineteen_ninetynine"
3
+
4
+ NineteenNinetynine.start
Binary file
@@ -0,0 +1,128 @@
1
+ module NineteenNinetynine
2
+ module Core
3
+ def _init
4
+ inits.each { |block| class_eval(&block) }
5
+ end
6
+ def users
7
+ @users ||= []
8
+ end
9
+
10
+ def start
11
+ _init
12
+
13
+ EM.run do
14
+ Thread.start do
15
+ while buf = Readline.readline("Nostr: ", true)
16
+ unless Readline::HISTORY.count == 1
17
+ Readline::HISTORY.pop if buf.empty? || Readline::HISTORY[-1] == Readline::HISTORY[-2]
18
+ end
19
+ #sync {
20
+ # reload unless config[:reload] == false
21
+ # store_history
22
+ # input(buf.strip)
23
+ #}
24
+ puts buf.strip
25
+ end
26
+ # unexpected
27
+ #stop
28
+ end
29
+
30
+ EM.add_periodic_timer(1) do
31
+ # Reconnect
32
+ # if @last_data_received_at && Time.now - @last_data_received_at > 30
33
+ # # stop_stream
34
+ # start_stream
35
+ # end
36
+
37
+ mutex = Mutex.new
38
+ mutex.synchronize do
39
+ output
40
+ end
41
+ end
42
+
43
+ start_stream
44
+ end
45
+ end
46
+
47
+ def stop_stream
48
+ @ws.close if @ws.open?
49
+ @ws = nil
50
+ end
51
+
52
+ def create_ws_client
53
+ @ws ||= WebSocket::Client::Simple.connect "wss://relay-jp.nostr.wirednet.jp"
54
+ end
55
+
56
+ def create_notes
57
+ @notes ||= []
58
+ end
59
+
60
+ def create_users
61
+ @users ||= []
62
+ end
63
+
64
+ def create_last_data_received_at
65
+ @last_data_received_at ||= Time.now
66
+ end
67
+
68
+ def last_data_received_at=(time)
69
+ @last_data_received_at = time
70
+ end
71
+
72
+ def start_stream
73
+ users = create_users
74
+ notes = create_notes
75
+ create_last_data_received_at
76
+
77
+ ws = create_ws_client
78
+
79
+ ws.on :message do |msg|
80
+ next if msg.data.empty?
81
+
82
+ payload = JSON.parse(msg.data)
83
+
84
+ case payload[0]
85
+ when "EOSE"
86
+ # puts "Start time line: #{Time.now}"
87
+ when "EVENT"
88
+ case payload[1]
89
+ when "content"
90
+ note = Event::Note.new(payload[2])
91
+ user = users.find { |u| u.pubkey == payload[2]["pubkey"] }
92
+ if user.nil?
93
+ ws.send JSON.generate(["REQ", "user", { kinds: [0], authors: [payload[2]["pubkey"]] }])
94
+
95
+ while user = users.find { |u| u.pubkey == payload[2]["pubkey"] }
96
+ note.user = user
97
+ sleep 0.1
98
+ end
99
+ else
100
+ note.user = user
101
+ end
102
+
103
+ notes.push note
104
+ when "user"
105
+ # user = User.new(JSON.parse(payload[2]["content"])["name"], payload[2]["pubkey"])
106
+ profile = Event::Profile.new(payload[2])
107
+ users.push profile
108
+ end
109
+ end
110
+ rescue JSON::ParserError => e
111
+ # ignore
112
+ end
113
+
114
+ ws.on :open do
115
+ ws.send JSON.generate(["REQ", "content", { kinds: [1], since: Time.now.to_i }])
116
+ ws.send JSON.generate(["REQ", "user", { kinds: [0] }])
117
+ end
118
+
119
+ ws.on :close do |e|
120
+ end
121
+
122
+ ws.on :error do |e|
123
+ puts e
124
+ puts e.backtrace
125
+ end
126
+ end
127
+ end
128
+ end
@@ -0,0 +1,16 @@
1
+ module NineteenNinetynine
2
+ class Event
3
+ class Note
4
+ attr_accessor :body, :user, :date, :pubkey, :raw, :_mark, :_stream, :sig
5
+ def initialize(content)
6
+ @raw = content
7
+ @body = content["content"]
8
+ @pubkey = content["pubkey"]
9
+ @date = Time.at content["created_at"]
10
+ @_mark = nil
11
+ @_stream = true
12
+ @sig = content["sig"]
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,70 @@
1
+ module NineteenNinetynine
2
+ class Event
3
+ class Profile
4
+ attr_accessor :name, :pubkey, :raw, :icon_path, :icon_io
5
+
6
+ def initialize(event)
7
+ @raw = event
8
+
9
+ @pubkey = event["pubkey"]
10
+ content = JSON.parse(event["content"])
11
+ @name = content["name"]
12
+ @picture_url = content["picture"]
13
+ set_icon
14
+
15
+ if !@picture_url.nil? && !@picture_url.empty?
16
+ unless File.exist?(icon_path)
17
+ Thread.start do
18
+ download_icon_image
19
+ end
20
+ end
21
+ end
22
+ end
23
+
24
+ def set_icon
25
+ if File.exist? icon_path
26
+ @icon_path = icon_path
27
+ else
28
+ @icon_path = icon_dir + "/default.png"
29
+ end
30
+ end
31
+
32
+ def icon_path
33
+ "#{icon_dir}/#{@pubkey}"
34
+ end
35
+
36
+ def icon_dir
37
+ "#{XDG_CONFIG_DIR}/icons"
38
+ end
39
+
40
+ def icon
41
+ `wezterm imgcat --height 1 #{@icon_path}`.strip
42
+ end
43
+
44
+ def download_icon_image
45
+ if @picture_url.start_with?("data:image/")
46
+ File.write(icon_path, Base64.decode64(@picture_url.split(",")[1]))
47
+ elsif @picture_url.start_with?("http")
48
+ url = URI.parse @picture_url
49
+ begin
50
+ res = Net::HTTP.get_response(url)
51
+ case res
52
+ when Net::HTTPSuccess, Net::HTTPRedirection
53
+ File.write(icon_path, res.body)
54
+ when Net::HTTPClientError, Net::HTTPServerError
55
+ # ignore
56
+ else
57
+ puts "unknown"
58
+ puts @picture_url
59
+ end
60
+ rescue SocketError, Net::OpenTimeout => e
61
+ # ignore
62
+ end
63
+ else
64
+ puts "Unknown schema"
65
+ puts @picture_url
66
+ end
67
+ end
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,4 @@
1
+ module NineteenNinetynine
2
+ class Event
3
+ end
4
+ end
@@ -0,0 +1,47 @@
1
+ class String
2
+ def c(*codes)
3
+ codes = codes.flatten.map { |code|
4
+ case code
5
+ when String, Symbol
6
+ Earthquake.config[:color][code.to_sym] rescue nil
7
+ else
8
+ code
9
+ end
10
+ }.compact.unshift(0)
11
+ "\e[#{codes.join(';')}m#{self}\e[0m"
12
+ end
13
+
14
+ def coloring(pattern, color = nil, &block)
15
+ self.gsub(pattern) do |i|
16
+ applied_colors = $`.scan(/\e\[[\d;]+m/)
17
+ c = color || block.call(i)
18
+ "#{i.c(c)}#{applied_colors.join}"
19
+ end
20
+ end
21
+
22
+ t = {
23
+ ?& => "&",
24
+ ?< => "&lt;",
25
+ ?> => "&gt;",
26
+ ?' => "&apos;",
27
+ ?" => "&quot;",
28
+ }
29
+
30
+ define_method(:u) do
31
+ gsub(/(#{Regexp.union(t.values)})/o, t.invert)
32
+ end
33
+
34
+ define_method(:e) do
35
+ gsub(/[#{t.keys.join}]/o, t)
36
+ end
37
+
38
+ def indent(count, char = ' ')
39
+ (char * count) + gsub(/(\n+)/) { |m| m + (char * count) }
40
+ end
41
+
42
+ def trim_indent
43
+ lines = self.split("\n")
44
+ unindent = self.split("\n").select { |s| s !~ /^\s$/ }.map { |s| s.index(/[^\s]/) || 0 }.min
45
+ lines.map { |s| s.gsub(/^#{' ' * unindent}/, '') }.join("\n")
46
+ end
47
+ end
@@ -0,0 +1,45 @@
1
+ module NineteenNinetynine
2
+ module IdVar
3
+ attr_accessor :id_var
4
+
5
+ def id2var(id)
6
+ id_var.id2var(id)
7
+ end
8
+
9
+ def var2id(var)
10
+ id_var.var2id(var)
11
+ end
12
+
13
+ class Gen
14
+ def initialize(vars = "aa".."zz", prefix = "$")
15
+ unless Range === vars and String === vars.first
16
+ raise ArgumentError, "vars should be a Range of String"
17
+ end
18
+ @vars = vars
19
+ @var = @vars.last.dup
20
+ @table = ActiveSupport::Cache::MemoryStore.new
21
+ @prefix = prefix
22
+ end
23
+
24
+ def var2id(var)
25
+ @table.read(var)
26
+ end
27
+
28
+ def id2var(id)
29
+ @table.read(id) || succ(id)
30
+ end
31
+
32
+ private
33
+
34
+ def succ(id)
35
+ @var.replace(@vars.first.dup) unless @vars.include?(@var.next!)
36
+ var = @prefix + @var
37
+ @table.delete(@table.read(var))
38
+ @table.write(var, id)
39
+ @table.write(id, var)
40
+ @table.write(@prefix + '_', id)
41
+ var.dup
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,11 @@
1
+ module NineteenNinetynine
2
+ module Initializer
3
+ def inits
4
+ @inits ||= []
5
+ end
6
+
7
+ def init(&block)
8
+ inits << block
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,84 @@
1
+ module NineteenNinetynine
2
+ module Output
3
+ def output(name = nil, &block)
4
+ if block
5
+ outputs.delete_if { |o| o[:name] == name } if name
6
+ outputs << { name: name, block: block }
7
+ else
8
+ insert do
9
+ while note = @notes.shift
10
+ if note.user.nil?
11
+ sleep 1
12
+ # users = $cache.read("users")
13
+ user = @users.find { |u| u.pubkey == note.raw["pubkey"] }
14
+ note.user = user
15
+ puts_items(note)
16
+ else
17
+ puts_items(note)
18
+ end
19
+ end
20
+ end
21
+ end
22
+ end
23
+
24
+ def output_filters
25
+ @output_filters ||= []
26
+ end
27
+
28
+ def output_filter(&block)
29
+ output_filters << block
30
+ end
31
+
32
+ def outputs
33
+ @outputs ||= []
34
+ end
35
+
36
+ def puts_items(items)
37
+ mark_color = colors.sample + 10
38
+
39
+ [items].flatten.reverse_each do |item|
40
+ next if output_filters.any? { |f| f.call(item) == false }
41
+
42
+ if item.body && !item._stream
43
+ item._mark = ' '.c(mark_color) + item._mark.to_s
44
+ end
45
+
46
+ outputs.each do |o|
47
+ begin
48
+ o[:block].call(item)
49
+ rescue => e
50
+ error e
51
+ end
52
+ end
53
+ end
54
+ end
55
+
56
+ def insert(*messages)
57
+ monitor.synchronize do
58
+ begin
59
+ try_swap = !$stdout.is_a?(StringIO)
60
+ $stdout = StringIO.new if try_swap
61
+
62
+ puts messages
63
+ yield if block_given?
64
+
65
+ unless $stdout.string.empty?
66
+ STDOUT.print "\e[0G\e[K#{$stdout.string}"
67
+ Readline.refresh_line
68
+ end
69
+ ensure
70
+ $stdout = STDOUT if try_swap
71
+ end
72
+ end
73
+ end
74
+
75
+ def monitor
76
+ @monitor ||= Monitor.new
77
+ end
78
+
79
+ def color_of(name)
80
+ colors = (31..36).to_a + (91..96).to_a
81
+ colors[name.delete("^0-9A-Za-z_").to_i(36) % colors.size]
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,25 @@
1
+ # require 'stringio'
2
+ # require 'monitor'
3
+
4
+ require_relative "initializer"
5
+
6
+ module NineteenNinetynine
7
+ module Renderer
8
+ attr_accessor :items, :users, :item_queue, :loaded
9
+ def items
10
+ @items ||= []
11
+ end
12
+
13
+ def users
14
+ @users ||= []
15
+ end
16
+
17
+ def item_queue
18
+ @item_queue ||= []
19
+ end
20
+
21
+ def colors
22
+ (31..36).to_a + (91..96).to_a
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,8 @@
1
+ require "websocket-client-simple"
2
+
3
+ module NineteenNinetynine
4
+ module Subscriber
5
+ def self.start
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,73 @@
1
+ require 'bech32'
2
+
3
+ module NineteenNinetynine
4
+ module Utils
5
+
6
+ def self.scripted_pubkey(pubkey)
7
+ addr = CustomAddr.new(pubkey)
8
+ addr.to_scriptpubkey
9
+ end
10
+
11
+ class CustomAddr
12
+ attr_accessor :hrp # human-readable part
13
+ attr_accessor :prog # witness program
14
+
15
+ def initialize(addr = nil)
16
+ @hrp, @prog = parse_addr(addr) if addr
17
+ end
18
+
19
+ def to_scriptpubkey
20
+ prog.map{|p|[p].pack("C")}.join.unpack("H*").first
21
+ end
22
+
23
+ def scriptpubkey=(script)
24
+ values = [script].pack("H*").unpack("C*")
25
+ @prog = values
26
+ end
27
+
28
+ def addr
29
+ spec = Bech32::Encoding::BECH32
30
+ Bech32.encode(hrp, convert_bits(prog, 8, 5), spec)
31
+ end
32
+
33
+ private
34
+
35
+ def parse_addr(addr)
36
+ hrp, data, spec = Bech32.decode(addr)
37
+
38
+ if hrp.nil? || data[0].nil?
39
+ puts addr
40
+ raise'Invalid address.'
41
+ end
42
+ # raise 'Invalid witness version' if ver > 16
43
+ prog = convert_bits(data, 5, 8, false)
44
+ # raise 'Invalid witness program' if prog.nil? || prog.length < 2 || prog.length > 40
45
+ # raise 'Invalid witness program with version 0' if ver == 0 && (prog.length != 20 && prog.length != 32)
46
+ [hrp, prog]
47
+ end
48
+
49
+ def convert_bits(data, from, to, padding=true)
50
+ acc = 0
51
+ bits = 0
52
+ ret = []
53
+ maxv = (1 << to) - 1
54
+ max_acc = (1 << (from + to - 1)) - 1
55
+ data.each do |v|
56
+ return nil if v < 0 || (v >> from) != 0
57
+ acc = ((acc << from) | v) & max_acc
58
+ bits += from
59
+ while bits >= to
60
+ bits -= to
61
+ ret << ((acc >> bits) & maxv)
62
+ end
63
+ end
64
+ if padding
65
+ ret << ((acc << (to - bits)) & maxv) unless bits == 0
66
+ elsif bits >= from || ((acc << (to - bits)) & maxv) != 0
67
+ return nil
68
+ end
69
+ ret
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module NineteenNinetynine
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,112 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "nineteen_ninetynine/version"
4
+
5
+ require_relative "nineteen_ninetynine/core"
6
+ require_relative "nineteen_ninetynine/ext"
7
+ require_relative "nineteen_ninetynine/renderer"
8
+ require_relative "nineteen_ninetynine/id_var"
9
+ require_relative "nineteen_ninetynine/initializer"
10
+ require_relative "nineteen_ninetynine/output"
11
+ require_relative "nineteen_ninetynine/subscriber"
12
+ require_relative "nineteen_ninetynine/event/note"
13
+ require_relative "nineteen_ninetynine/event/profile"
14
+ require_relative "nineteen_ninetynine/utils"
15
+
16
+ require "active_support/cache"
17
+ require "active_support/notifications"
18
+ require "eventmachine"
19
+ require "fileutils"
20
+ require "json"
21
+ require "monitor"
22
+ require "net/http"
23
+ require "readline"
24
+ require "stringio"
25
+ require "thread"
26
+ require "uri"
27
+
28
+ module NineteenNinetynine
29
+ extend Core
30
+ extend Initializer
31
+ extend Renderer
32
+ extend Output
33
+ extend IdVar
34
+
35
+ User = Data.define :name, :pubkey
36
+
37
+ class Error < StandardError; end
38
+ XDG_CONFIG_DIR = "#{ENV['HOME']}/.config/1999"
39
+ @users = []
40
+ @items = []
41
+
42
+ unless Dir.exist?(XDG_CONFIG_DIR)
43
+ FileUtils.mkdir_p(XDG_CONFIG_DIR)
44
+ FileUtils.mkdir_p(XDG_CONFIG_DIR + "/icons")
45
+ FileUtils.cp(File.dirname(__FILE__) + "../assets/default.png", XDG_CONFIG_DIR + "/icons/default.png")
46
+ end
47
+
48
+ init do
49
+ self.id_var ||= IdVar::Gen.new
50
+ outputs.clear
51
+ output_filters.clear
52
+ config = {}
53
+
54
+ config[:colors] ||= (31..36).to_a + (91..96).to_a
55
+ config[:color] ||= {}
56
+ config[:color].merge!(
57
+ info: 90,
58
+ notice: 31,
59
+ event: 42,
60
+ url: [4, 36],
61
+ )
62
+ config[:raw_text] ||= true
63
+
64
+ output :note do |item|
65
+ info = []
66
+
67
+ id = id2var(item.sig)
68
+
69
+ text = item.body
70
+
71
+ if /\n/ =~ text
72
+ text.prepend("\n")
73
+ text.gsub!(/\n/, "\n " + "|".c(:info))
74
+ text << "\n "
75
+ else
76
+ text.gsub!(/\s+/, ' ')
77
+ end
78
+ text = text.coloring(/@[0-9A-Za-z_]+/) { |i| color_of(i) }
79
+ text = text.coloring(/(^#[^\s]+)|(\s+#[^\s]+)/) { |i| color_of(i) }
80
+ # if config[:expand_url]
81
+ # entities = (item["retweeted_status"] && item["truncated"]) ? item["retweeted_status"]["entities"] : item["entities"]
82
+ # if entities
83
+ # entities.values_at("urls", "media").flatten.compact.each do |entity|
84
+ # url, expanded_url = entity.values_at("url", "expanded_url")
85
+ # if url && expanded_url
86
+ # text = text.sub(url, expanded_url)
87
+ # end
88
+ # end
89
+ # end
90
+ # end
91
+ text = text.coloring(URI.regexp(["http", "https"]), :url)
92
+
93
+ # if item["_highlights"]
94
+ # item["_highlights"].each do |h|
95
+ # color = config[:color][:highlight].nil? ? color_of(h).to_i + 10 : :highlight
96
+ # text = text.coloring(/#{h}/i, color)
97
+ # end
98
+ # end
99
+
100
+ mark = item._mark || ""
101
+
102
+ status = [
103
+ item.date.strftime("%H:%M").c(:info),
104
+ mark + id.c(:info),
105
+ "#{item.user.icon}#{item.user.name.c(color_of(item.user.name))}:",
106
+ text,
107
+ info.join(' - ').c(:info),
108
+ ].compact.join(" ")
109
+ puts status
110
+ end
111
+ end
112
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/nineteen_ninetynine/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "nineteen_ninetynine"
7
+ spec.version = NineteenNinetynine::VERSION
8
+ spec.authors = ["Yuya Fujiwara"]
9
+ spec.email = ["hzw1258@gmail.com"]
10
+
11
+ spec.summary = "nineteen_ninetynine is nostr client"
12
+ spec.description = "nineteen_ninetynine is nostr client"
13
+ spec.homepage = "https://ason.as"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 3.2.0"
16
+
17
+
18
+ spec.metadata["homepage_uri"] = spec.homepage
19
+ spec.metadata["source_code_uri"] = "https://github.com/asonas/nineteen_ninetynine"
20
+ spec.metadata["changelog_uri"] = "https://github.com/asonas/nineteen_ninetynine"
21
+
22
+ # Specify which files should be added to the gem when it is released.
23
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
24
+ spec.files = Dir.chdir(__dir__) do
25
+ `git ls-files -z`.split("\x0").reject do |f|
26
+ (f == __FILE__) || f.match(%r{\A(?:(?:bin|test|spec|features)/|\.(?:git|circleci)|appveyor)})
27
+ end
28
+ end
29
+ spec.bindir = "exe"
30
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
31
+ spec.require_paths = ["lib"]
32
+
33
+ spec.add_dependency "activesupport"
34
+ spec.add_dependency "eventmachine"
35
+ spec.add_dependency "bech32"
36
+
37
+ # For more information and examples about making a new gem, check out our
38
+ # guide at: https://bundler.io/guides/creating_gem.html
39
+ end
@@ -0,0 +1,4 @@
1
+ module NineteenNinetynine
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,114 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: nineteen_ninetynine
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Yuya Fujiwara
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-06-22 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: eventmachine
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: bech32
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ description: nineteen_ninetynine is nostr client
56
+ email:
57
+ - hzw1258@gmail.com
58
+ executables:
59
+ - nineteen_ninetynine
60
+ extensions: []
61
+ extra_rdoc_files: []
62
+ files:
63
+ - ".rspec"
64
+ - ".rubocop.yml"
65
+ - CHANGELOG.md
66
+ - CODE_OF_CONDUCT.md
67
+ - Gemfile
68
+ - LICENSE.txt
69
+ - README.md
70
+ - Rakefile
71
+ - exe/nineteen_ninetynine
72
+ - lib/assets/default.png
73
+ - lib/nineteen_ninetynine.rb
74
+ - lib/nineteen_ninetynine/core.rb
75
+ - lib/nineteen_ninetynine/event.rb
76
+ - lib/nineteen_ninetynine/event/note.rb
77
+ - lib/nineteen_ninetynine/event/profile.rb
78
+ - lib/nineteen_ninetynine/ext.rb
79
+ - lib/nineteen_ninetynine/id_var.rb
80
+ - lib/nineteen_ninetynine/initializer.rb
81
+ - lib/nineteen_ninetynine/output.rb
82
+ - lib/nineteen_ninetynine/renderer.rb
83
+ - lib/nineteen_ninetynine/subscriber.rb
84
+ - lib/nineteen_ninetynine/utils.rb
85
+ - lib/nineteen_ninetynine/version.rb
86
+ - nineteen_ninetynine.gemspec
87
+ - sig/nineteen_ninetynine.rbs
88
+ homepage: https://ason.as
89
+ licenses:
90
+ - MIT
91
+ metadata:
92
+ homepage_uri: https://ason.as
93
+ source_code_uri: https://github.com/asonas/nineteen_ninetynine
94
+ changelog_uri: https://github.com/asonas/nineteen_ninetynine
95
+ post_install_message:
96
+ rdoc_options: []
97
+ require_paths:
98
+ - lib
99
+ required_ruby_version: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: 3.2.0
104
+ required_rubygems_version: !ruby/object:Gem::Requirement
105
+ requirements:
106
+ - - ">="
107
+ - !ruby/object:Gem::Version
108
+ version: '0'
109
+ requirements: []
110
+ rubygems_version: 3.4.6
111
+ signing_key:
112
+ specification_version: 4
113
+ summary: nineteen_ninetynine is nostr client
114
+ test_files: []