leetcoder 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: a695bd749e273d75cc9b1f0fd871f897471f9da4381b33b95717e7a278c20316
4
+ data.tar.gz: c9ef673c5aed97868002a8d03517836f8c9babc4d61366baf0996df513cfdad9
5
+ SHA512:
6
+ metadata.gz: 3c298b6ad2567f858b35b6a16b2f59b7f73ae45850da5d26be7209b70271ed20ca30f3b101b977f6fe09c2118d4d6efc76d90d80ecdc328ebc2e42111491949a
7
+ data.tar.gz: 91ca7837e54a0e4f955ca2562750c59c3e45b104ca70afa8999b294a36fcb455f81b6f991b5167d5daa4648f28e30ad9774cf90f6b44de6dbacd36eee6505b50
data/.env.sample ADDED
@@ -0,0 +1 @@
1
+ LEETCODE_COOKIE='paste the leetcode cookie here'
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,107 @@
1
+ require:
2
+ - rubocop-performance
3
+ - rubocop-rspec
4
+
5
+ AllCops:
6
+ TargetRubyVersion: 3.1.1
7
+ NewCops: enable
8
+ SuggestExtensions: false
9
+ Exclude:
10
+ - vendor/**/*
11
+ - tmp/**/*
12
+ - leetcode/**/*
13
+
14
+ Layout/SpaceInsideHashLiteralBraces:
15
+ EnforcedStyle: space
16
+
17
+ Metrics/BlockLength:
18
+ Max: 36
19
+ Exclude:
20
+ - spec/**/*.rb
21
+ - leetcoder.gemspec
22
+ IgnoredMethods:
23
+ - configure
24
+
25
+ Metrics/BlockNesting:
26
+ Max: 2
27
+
28
+ RSpec/ContextWording:
29
+ Prefixes:
30
+ - for
31
+ - when
32
+ - with
33
+ - without
34
+
35
+ Metrics/AbcSize:
36
+ IgnoredMethods:
37
+ - change
38
+ - query
39
+
40
+ Metrics/MethodLength:
41
+ CountComments: false
42
+ Max: 15
43
+ IgnoredMethods:
44
+ - change
45
+ - up
46
+
47
+ Layout/LineLength:
48
+ AllowURI: true
49
+
50
+ Metrics/ModuleLength:
51
+ Max: 120
52
+
53
+ Metrics/ClassLength:
54
+ Max: 120
55
+
56
+ Metrics/ParameterLists:
57
+ Max: 5
58
+ CountKeywordArgs: true
59
+
60
+ Style/CollectionMethods:
61
+ Enabled: true
62
+ PreferredMethods:
63
+ collect: 'map'
64
+ collect!: 'map!'
65
+ inject: 'reduce'
66
+ find: 'detect'
67
+ find_all: 'select'
68
+ delete: 'gsub'
69
+
70
+ Layout/DotPosition:
71
+ EnforcedStyle: leading
72
+
73
+ Style/TrailingCommaInArrayLiteral:
74
+ EnforcedStyleForMultiline: 'no_comma'
75
+
76
+ Style/TrailingCommaInHashLiteral:
77
+ EnforcedStyleForMultiline: 'no_comma'
78
+
79
+ Style/Documentation:
80
+ Enabled: false
81
+
82
+ Style/OpenStructUse:
83
+ Enabled: false
84
+
85
+ RSpec/ExampleLength:
86
+ Max: 35
87
+
88
+ RSpec/FilePath:
89
+ Enabled: false
90
+
91
+ RSpec/MultipleMemoizedHelpers:
92
+ Max: 10
93
+
94
+ RSpec/DescribeClass:
95
+ Enabled: false
96
+
97
+ RSpec/NestedGroups:
98
+ Max: 6
99
+
100
+ RSpec/MultipleExpectations:
101
+ Max: 10
102
+
103
+ RSpec/RepeatedExampleGroupBody:
104
+ Enabled: false
105
+
106
+ Gemspec/RequireMFA:
107
+ Enabled: false
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 3.1.1
data/CHANGELOG.md ADDED
@@ -0,0 +1,6 @@
1
+ ## [Released]
2
+
3
+ ## [0.1.0] - 2022-08-09
4
+
5
+ - Initial release
6
+ - Download Accepted Leetcode Submission with Problem Readme
@@ -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 imam.swe@gmail.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/Dockerfile ADDED
@@ -0,0 +1,8 @@
1
+ # syntax=docker/dockerfile:1
2
+ FROM ruby:3.1.1
3
+ RUN apt-get update -qq
4
+ WORKDIR /leetcoder
5
+
6
+ RUN gem install leetcoder
7
+
8
+ ENTRYPOINT ["/bin/bash"]
data/Gemfile ADDED
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in leetcoder.gemspec
6
+ gemspec
7
+
8
+ group :development, :test do
9
+ gem 'awesome_print'
10
+ gem 'dotenv'
11
+ gem 'pry'
12
+ gem 'rake', '~> 13.0'
13
+ end
14
+
15
+ # test
16
+ group :test do
17
+ gem 'rspec', '~> 3.11'
18
+ gem 'rubocop', '~> 1.32'
19
+ gem 'rubocop-performance', '~> 1.14'
20
+ gem 'rubocop-rspec', '~> 2.12'
21
+ gem 'vcr', '~> 6.1'
22
+ gem 'webmock', '~> 3.14'
23
+ end
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Imam Hossain
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,31 @@
1
+ # LeetCoder
2
+
3
+ <!-- ![Leetcoder](/spec/cassettes/leetcoder.png) -->
4
+ <img src="/spec/cassettes/leet_coder.png" alt="leetcoder" float="right" height="300px"/>
5
+
6
+ A Ruby Leetcode Client to help you download all your accepted Leetcode submissions with problem description.
7
+
8
+ ## Installation
9
+
10
+ ```
11
+ gem install leetcoder
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ ```
17
+ Usage: leetcoder [command]
18
+
19
+ * indicates default value
20
+
21
+ commands:
22
+ -d, --download [TYPE] Specify number of accepted submission to download per problem (*one, all)
23
+ -c, --cookie Input Leetcode Cookie
24
+ -f, --folder FOLDER_PATH Specify download folder location (* <current_directory>/leetcode)
25
+ -v, --version Show version
26
+ -h, --help Show available commands
27
+ ```
28
+
29
+ ## Authors
30
+ Imam Hossain <br>
31
+ Email: imam.swe@gmail.com
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]
data/bin/leetcoder ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'leetcoder/leetcoder'
5
+
6
+ Leetcoder::Cli.start
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'optparse'
4
+
5
+ module Leetcoder
6
+ class Cli
7
+ include Helpers::ErrorHandler
8
+ attr_reader :args, :commands
9
+
10
+ def initialize(args)
11
+ @args = args
12
+ @commands = Commands.new
13
+ end
14
+
15
+ def self.start(args = ARGV.dup)
16
+ new(args).start
17
+ end
18
+
19
+ def start
20
+ error_handler do
21
+ option_parser
22
+ end
23
+ end
24
+
25
+ private
26
+
27
+ def option_parser
28
+ OptionParser.new do |parser|
29
+ commands.define_commands(parser)
30
+ parser.parse!(args)
31
+ commands.run!
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'faraday'
4
+ require 'faraday/net_http'
5
+
6
+ module Leetcoder
7
+ class Client
8
+ class ApiError < StandardError; end
9
+ class AuthenticationError < StandardError; end
10
+ class InvalidCookie < StandardError; end
11
+
12
+ def initialize(_args = {})
13
+ @cookie = ENV.fetch('LEETCODE_COOKIE', nil) || read_cookie
14
+ end
15
+
16
+ # @params
17
+ # request_type: [get, post, put, delete]
18
+ # endpoint: part of the url after base url
19
+ # payload: request body payload
20
+ # params: filter params
21
+ def call(request_type, endpoint, payload: {}, params: {})
22
+ response = connection.public_send(request_type, endpoint) do |req|
23
+ req.body = payload
24
+ req.params = params
25
+ req.headers['Cookie'] = cookie
26
+ req.headers['Referer'] = BASE_URL
27
+ req.headers['X-csrftoken'] = x_csrftoken
28
+ end
29
+
30
+ return response if valid_response?(response)
31
+
32
+ client_error_handler(response)
33
+ end
34
+
35
+ def connection
36
+ @connection ||= Faraday.new(url: Leetcoder::BASE_URL) do |f|
37
+ f.request :json
38
+ f.response :json, content_type: /\bjson$/, parser_options: { symbolize_names: true }
39
+ f.request :multipart
40
+ f.adapter :net_http
41
+ end
42
+ end
43
+
44
+ private
45
+
46
+ attr_reader :cookie
47
+
48
+ def valid_response?(response)
49
+ return false unless (200...299).cover?(response.status)
50
+ return true unless response.body.is_a? Hash
51
+
52
+ response.body[:errors].nil? # additional check for graphql response
53
+ end
54
+
55
+ def read_cookie
56
+ Base64.urlsafe_decode64(File.read(COOKIE_FILE))
57
+ rescue StandardError
58
+ raise AuthenticationError, 'Authentication Error! Please provide a valid leetcode cookie.'
59
+ end
60
+
61
+ # ?<= positive lookbehind ( precedded by )
62
+ # ?= positivie lookahead ( followed by )
63
+ # .*? non greedy match ( capture first matched group )
64
+ def x_csrftoken
65
+ cookie.match(/(?<=csrftoken=).*?(?=;)/)[0]
66
+ rescue StandardError
67
+ raise InvalidCookie, 'The cookie you entered is not valid. Please provide a valid leetcode cookie.'
68
+ end
69
+
70
+ def client_error_handler(response)
71
+ case response.status
72
+ when 200, 400
73
+ raise ApiError, "status: #{response.status},\n" \
74
+ "code: GRAPHQL_ERROR, \nerrors: #{response.body[:errors]}"
75
+ when 404
76
+ raise ApiError, "status: #{response.status},\n" \
77
+ "code: NOT_FOUND_ERROR,\n" \
78
+ "errors: [The resource you are looking for couldn't be found!]"
79
+ else
80
+ raise ApiError, "status: #{response.status},\n" \
81
+ "full_response: #{response.inspect.gsub(/"Cookie.*?",/, '<cookie>')}"
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leetcoder
4
+ class Collection
5
+ attr_reader :data
6
+
7
+ def self.from_response(response, key:, type: Object)
8
+ response.dig(*key).map { |attrs| type.new(attrs) }
9
+ # response.dig(*key[0...-1], 'total')
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'optparse'
4
+
5
+ module Leetcoder
6
+ class Commands
7
+ include Helpers::Utils
8
+
9
+ DOWNLOAD_TYPE_ONE = :one
10
+ DOWNLOAD_TYPE_ALL = :all
11
+
12
+ attr_reader :options
13
+
14
+ def initialize(options = {})
15
+ @options = options
16
+ end
17
+
18
+ def run!
19
+ Leetcoder::Download.call(options)
20
+ end
21
+
22
+ def define_commands(parser) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize
23
+ parser.banner = 'Usage: leetcoder [commands]'
24
+ parser.separator ''
25
+ parser.separator '* indicates default value'
26
+ parser.separator ''
27
+ parser.separator 'commands:'
28
+
29
+ parser.on(
30
+ '-d',
31
+ '--download [TYPE]',
32
+ [DOWNLOAD_TYPE_ALL, DOWNLOAD_TYPE_ONE],
33
+ 'Specify number of accepted submission to download per problem (*one, all)'
34
+ ) do |type|
35
+ options[:download_type] = type || DOWNLOAD_TYPE_ONE
36
+ end
37
+
38
+ parser.on('-c', '--cookie', String, 'Input Leetcode Cookie') do
39
+ store_cookie
40
+ exit
41
+ end
42
+
43
+ parser.on('-f', '--folder FOLDER_PATH', String,
44
+ 'Specify download folder location (* <current_directory>/leetcode)') do |folder|
45
+ options[:download_folder] = File.expand_path(folder)
46
+ end
47
+
48
+ parser.on_tail('-v', '--version', 'Show version') do
49
+ puts Leetcoder::VERSION
50
+ exit
51
+ end
52
+
53
+ parser.on_tail('-h', '--help', 'Show available commands') do
54
+ puts parser
55
+ exit
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leetcoder
4
+ class Download
5
+ include Helpers::Utils
6
+ include Helpers::Logger
7
+
8
+ def initialize(args)
9
+ @args = args
10
+ @question_resource = QuestionsResource.new
11
+ @root_directory = create_directory(args[:download_folder] || 'leetcode')
12
+ end
13
+
14
+ def self.call(args = {})
15
+ new(args).call
16
+ end
17
+
18
+ def call
19
+ Dir.chdir(@root_directory) do
20
+ download_accepted_submissions
21
+ end
22
+ end
23
+
24
+ private
25
+
26
+ attr_reader :args
27
+
28
+ def download_accepted_submissions
29
+ accepted_questions.each do |question|
30
+ question_dir = "#{question.frontendQuestionId}.#{question.titleSlug}"
31
+ next log_message(:skip, question_dir:) unless Dir.glob("#{question_dir}/*solution*").empty?
32
+
33
+ log_message(:download, question_dir:)
34
+
35
+ Dir.chdir(create_directory(question_dir)) do
36
+ process_question(question)
37
+ process_submissions(question)
38
+ end
39
+ end
40
+ end
41
+
42
+ def accepted_questions
43
+ QuestionsResource.new.accepted_list.tap do |data|
44
+ raise Errors::NoAcceptedQuestions if data.empty?
45
+ end
46
+ end
47
+
48
+ def process_question(question)
49
+ question_data = QuestionsResource.new.retrieve(question.titleSlug)
50
+ Question.new(question_data).save_to_file!
51
+ end
52
+
53
+ def process_submissions(question)
54
+ accepted_submissions(question).each_with_index do |sub, index|
55
+ submission_data = SubmissionsResource.new.retrieve(url: sub.url)
56
+
57
+ Submission.new(submission_data, index: index + 1).save_to_file!
58
+ end
59
+ end
60
+
61
+ def accepted_submissions(question)
62
+ resource = SubmissionsResource.new(title_slug: question.titleSlug)
63
+ return resource.accepted_list if args[:download_type] == Commands::DOWNLOAD_TYPE_ALL
64
+
65
+ resource.uniq_accepted_list # default list
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leetcoder
4
+ class Error < StandardError; end
5
+
6
+ module Errors
7
+ class EmptyCommand < Leetcoder::Error; end
8
+ class InvalidCommand < Leetcoder::Error; end
9
+
10
+ class NoAcceptedQuestions < Leetcoder::Error
11
+ def to_s
12
+ 'No accepted problems found on your account.' \
13
+ 'Please update LEETCODE COOKIE and try again if you think this is an error.'
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leetcoder
4
+ module Helpers
5
+ module ErrorHandler
6
+ # wrap code block with error_hanlder do; end to rescue errors
7
+ def error_handler
8
+ yield
9
+ rescue OptionParser::InvalidArgument, OptionParser::InvalidOption => e
10
+ puts "error: #{e}"
11
+ puts help_toast
12
+ rescue Errors::EmptyCommand
13
+ puts "Hi there! Please provide a valid command! #{help_toast} "
14
+ rescue Errors::InvalidCommand
15
+ puts "Invalid Command! #{help_toast}"
16
+ rescue StandardError => e
17
+ puts "error: #{e}"
18
+ puts e.backtrace if ENV['TEST']
19
+ end
20
+
21
+ def help_toast
22
+ "\nRun `leetcoder --help` to see available commands."
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leetcoder
4
+ module Helpers
5
+ module GqlQueries
6
+ def default_limit = ENV['TEST'] ? 5 : -1
7
+
8
+ def problemset_query(args = {})
9
+ <<~GQL
10
+ query problemsetQuestionList($filters: QuestionListFilterInput) {
11
+ problemsetQuestionList: questionList(
12
+ categorySlug: "#{args.fetch(:categorySlug, 'algorithms')}",
13
+ limit: #{args.fetch(:limit, default_limit)},
14
+ skip: #{args.fetch(:skip, 0)},
15
+ filters: $filters
16
+ ) {
17
+ total: totalNum
18
+ questions: data {
19
+ acRate
20
+ difficulty
21
+ freqBar
22
+ frontendQuestionId: questionFrontendId
23
+ isFavor
24
+ paidOnly: isPaidOnly
25
+ status
26
+ title
27
+ titleSlug
28
+ topicTags {
29
+ name
30
+ id
31
+ slug
32
+ }
33
+ hasSolution
34
+ hasVideoSolution
35
+ }
36
+ }
37
+ }
38
+ GQL
39
+ end
40
+
41
+ def question_data_query(args = {})
42
+ <<~GQL
43
+ query questionData {
44
+ question(titleSlug: "#{args[:title_slug]}") {
45
+ questionId
46
+ title
47
+ titleSlug
48
+ content
49
+ difficulty
50
+ categoryTitle
51
+ stats
52
+ topicTags {
53
+ name
54
+ slug
55
+ translatedName
56
+ }
57
+ likes dislikes isLiked similarQuestions exampleTestcases
58
+ }
59
+ }
60
+ GQL
61
+ end
62
+
63
+ def submissions_query(args = {})
64
+ <<~GQL
65
+ query Submissions {
66
+ submissionList(
67
+ questionSlug: "#{args[:title_slug]}",
68
+ limit: #{args.fetch(:limit, default_limit)},
69
+ offset: #{args.fetch(:skip, 0)}
70
+ ) {
71
+ lastKey
72
+ hasNext
73
+ submissions {
74
+ id
75
+ statusDisplay
76
+ lang
77
+ runtime
78
+ timestamp
79
+ url
80
+ isPending
81
+ memory
82
+ }
83
+ }
84
+ }
85
+ GQL
86
+ end
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leetcoder
4
+ module Helpers
5
+ module Logger
6
+ def log_message(key, **args)
7
+ puts message(key, args)
8
+ end
9
+
10
+ private
11
+
12
+ def message(key, args)
13
+ case key
14
+ when :skip
15
+ "Skipping Download for #{args[:question_dir]}. Already Exist."
16
+ when :download
17
+ "Downloading sumbimissions for #{args[:question_dir]}"
18
+ end
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leetcoder
4
+ module Helpers
5
+ module Utils
6
+ LANGS_EXT = {
7
+ bash: 'sh',
8
+ c: 'c',
9
+ cpp: 'cpp',
10
+ csharp: 'cs',
11
+ golang: 'go',
12
+ java: 'java',
13
+ javascript: 'js',
14
+ kotlin: 'kt',
15
+ mysql: 'sql',
16
+ php: 'php',
17
+ python: 'py',
18
+ python3: 'py',
19
+ ruby: 'rb',
20
+ rust: 'rs',
21
+ scala: 'scala',
22
+ swift: 'swift'
23
+ }.freeze
24
+
25
+ def lang_to_ext(lang)
26
+ LANGS_EXT[lang.to_sym]
27
+ end
28
+
29
+ def create_directory(name)
30
+ FileUtils.mkdir_p(name).first
31
+ end
32
+
33
+ # create an empty file and return the path
34
+ # ex: create_file('~/leetcode/secret.txt')
35
+ def create_file(file_path)
36
+ FileUtils.mkdir_p(file_path.match(%r{.*(?=/)})[0]).then do
37
+ FileUtils.touch(file_path).first
38
+ end
39
+ end
40
+
41
+ def store_cookie
42
+ puts 'Please paste your leetcode cookie below:'
43
+ print ':>'
44
+ cookie = $stdin.gets("\n").chomp
45
+
46
+ File.write(create_file(COOKIE_FILE), Base64.urlsafe_encode64(cookie))
47
+
48
+ puts "\nCookie is saved successfully! You can now access protected resources."
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'ostruct'
4
+
5
+ module Leetcoder
6
+ class Object < OpenStruct
7
+ def initialize(attributes)
8
+ super to_ostruct(attributes)
9
+ end
10
+
11
+ def self.from_response(response, key:)
12
+ new(response.dig(*key))
13
+ end
14
+
15
+ def self.from_html(html)
16
+ Nokogiri::HTML(html)
17
+ end
18
+
19
+ def to_ostruct(obj)
20
+ case obj.class
21
+ when Hash
22
+ OpenStruct.new(obj.tranform_values { |val| to_ostruct(val) })
23
+ when Array
24
+ obj.map { |o| to_ostruct(o) }
25
+ else # Assumed to be a primitive value
26
+ obj
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leetcoder
4
+ class BaseObject
5
+ attr_reader :object, :args
6
+
7
+ def initialize(object, **args)
8
+ @object = object
9
+ @args = args
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leetcoder
4
+ class Question < BaseObject
5
+ def save_to_file!
6
+ File.write('README.md', question_data)
7
+ end
8
+
9
+ def question_data
10
+ serialized_data.map { |key, value| block_format(key, value) }.join("<br> \n")
11
+ end
12
+
13
+ def serialized_data
14
+ {
15
+ title: object.title,
16
+ url:,
17
+ topic_tags:,
18
+ difficulty: object.difficulty,
19
+ content: object.content,
20
+ stats:,
21
+ likes: object.likes
22
+ }
23
+ end
24
+
25
+ def url
26
+ "#{Leetcoder::BASE_URL}/problems/#{object.titleSlug}"
27
+ end
28
+
29
+ def topic_tags
30
+ object.topicTags.map { |tag| "##{tag[:slug]}" }.join(', ')
31
+ end
32
+
33
+ def stats
34
+ JSON.parse(object.stats).slice(*%w[totalAccepted totalSubmission acRate]).map do |key, value|
35
+ "#{key.upcase}: #{value}"
36
+ end.join(', ')
37
+ end
38
+
39
+ private
40
+
41
+ def block_format(key, value)
42
+ return "\n<br>#{value}" if key == :content
43
+
44
+ "<b> #{titelize(key)} :</b> #{value}"
45
+ end
46
+
47
+ def titelize(str)
48
+ str.to_s.split('_').map(&:capitalize).join(' ')
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'leetcoder/leetcoder/helpers/utils'
4
+
5
+ module Leetcoder
6
+ class Submission < BaseObject
7
+ include Leetcoder::Helpers::Utils
8
+
9
+ def save_to_file!
10
+ File.write(file_name, code)
11
+ end
12
+
13
+ def code
14
+ code = submission_data.scan(/(?<=submissionCode:).*'/).first.strip
15
+
16
+ code.gsub!(/\\u(.{4})/) { |_match| [Regexp.last_match(1).to_i(16)].pack('U') }
17
+
18
+ code.gsub!(/\A'|'\Z/, '')
19
+ end
20
+
21
+ def file_name
22
+ name_prefix = "#{question_id}.solution#{serial}"
23
+ # name_prefix += serial if serial
24
+ "#{name_prefix}.#{lang_to_ext(lang)}"
25
+ end
26
+
27
+ private
28
+
29
+ def serial
30
+ return nil if args[:index].nil? || args[:index] < 2
31
+
32
+ args[:index].to_s
33
+ end
34
+
35
+ def lang
36
+ submission_data.scan(/(?<=getLangDisplay: ').*(?=')/).first.strip
37
+ end
38
+
39
+ def question_id
40
+ submission_data.scan(/(?<=questionId: ').*(?=')/).first.strip
41
+ end
42
+
43
+ def submission_data
44
+ object.search('script').text
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leetcoder
4
+ class BaseResource
5
+ include Helpers::GqlQueries
6
+
7
+ class Response < Object; end
8
+
9
+ attr_reader :args
10
+
11
+ def initialize(args = {})
12
+ @client = Client.new
13
+ @args = args
14
+ end
15
+
16
+ # @params: file_path:string, request:proc
17
+ # cache response in file_path and return it
18
+ def cache_response(file_path, request, update: false)
19
+ data = YAML.load_file(file_path) if File.exist? file_path
20
+ return Response.new(body: data) unless update || data.nil?
21
+
22
+ puts 'Caching Response..'
23
+
24
+ request.call.tap do |response|
25
+ File.write(file_path, response.body.to_yaml)
26
+ end
27
+ end
28
+
29
+ def get_request(endpoint, params: {})
30
+ @client.call('get', endpoint, params:)
31
+ end
32
+
33
+ def post_request(endpoint, payload: {}, params: {})
34
+ @client.call('post', endpoint, payload:, params:)
35
+ end
36
+
37
+ def gql_request(query: {}, variables: {})
38
+ @client.call('post', 'graphql', payload: { query:, variables: })
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leetcoder
4
+ class QuestionsResource < BaseResource
5
+ # returns the list of only accepted leetcode problems
6
+ def accepted_list
7
+ response = gql_request(query: problemset_query, variables: { filters: { status: 'AC' } })
8
+
9
+ Collection.from_response(response.body, key: %i[data problemsetQuestionList questions])
10
+ end
11
+
12
+ # # returns the list of all leetcode problems, not usued
13
+ def list
14
+ request = proc { gql_request(query: problemset_query, variables: { filters: {} }) }
15
+
16
+ response = cache_response('questions_cache.yml', request, update: false)
17
+ Collection.from_response(response.body, key: %i[data problemsetQuestionList questions])
18
+ end
19
+
20
+ # returns a single problem data
21
+ def retrieve(title_slug)
22
+ response = gql_request(query: question_data_query(title_slug:))
23
+
24
+ Object.from_response(response.body, key: %i[data question])
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leetcoder
4
+ class SubmissionsResource < BaseResource
5
+ # returns a list of all the submissions for a problem
6
+ def list
7
+ response = gql_request(query: submissions_query(**args.slice(:title_slug)))
8
+
9
+ Collection.from_response(response.body, key: %i[data submissionList submissions])
10
+ end
11
+
12
+ # returns a list of accepted submissions of the problem
13
+ def accepted_list
14
+ @accepted_list ||= list.select do |submission|
15
+ submission.statusDisplay == 'Accepted'
16
+ end
17
+ end
18
+
19
+ # returns a list of latest accepted submission from each language
20
+ def uniq_accepted_list
21
+ accepted_list
22
+ .group_by(&:lang)
23
+ .map { |x| x[1].first }
24
+ end
25
+
26
+ # returns the html object for a single submission
27
+ def retrieve(url:)
28
+ response = get_request(url)
29
+
30
+ Object.from_html(response.body)
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leetcoder
4
+ VERSION = '0.1.1'
5
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Dir[File.join(__dir__, 'leetcoder', '**', '*.rb')].each { |file| require file }
4
+
5
+ require 'base64'
6
+ require 'fileutils'
7
+ require 'nokogiri'
8
+ require 'yaml'
9
+ require_relative 'leetcoder/version'
10
+ require_relative 'leetcoder/client'
11
+ require_relative 'leetcoder/collection'
12
+ require_relative 'leetcoder/object'
13
+ require_relative 'leetcoder/errors'
14
+ require_relative 'leetcoder/helpers/error_handler'
15
+ require_relative 'leetcoder/helpers/gql_queries'
16
+ require_relative 'leetcoder/helpers/logger'
17
+ require_relative 'leetcoder/helpers/utils'
18
+ require_relative 'leetcoder/objects/base_object'
19
+ require_relative 'leetcoder/objects/submission'
20
+ require_relative 'leetcoder/objects/question'
21
+ require_relative 'leetcoder/resources/base_resource'
22
+ require_relative 'leetcoder/resources/questions'
23
+ require_relative 'leetcoder/resources/submissions'
24
+ require_relative 'leetcoder/download'
25
+ require_relative 'leetcoder/commands'
26
+ require_relative 'leetcoder/cli'
27
+
28
+ module Leetcoder
29
+ BASE_URL = 'https://leetcode.com'
30
+ CONFIG_DIR = File.expand_path('~/.leetcoder')
31
+ COOKIE_FILE = "#{CONFIG_DIR}/secret.txt".freeze
32
+ end
metadata ADDED
@@ -0,0 +1,109 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: leetcoder
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - Imam Hossain
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2022-08-08 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: faraday
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.10'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.10'
27
+ - !ruby/object:Gem::Dependency
28
+ name: nokogiri
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.13'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.13'
41
+ description: A Ruby Leetcode Client to download and backup your submissions with problem
42
+ description
43
+ email:
44
+ - imam.swe@gmail.com
45
+ executables:
46
+ - leetcoder
47
+ extensions: []
48
+ extra_rdoc_files: []
49
+ files:
50
+ - ".env.sample"
51
+ - ".rspec"
52
+ - ".rubocop.yml"
53
+ - ".ruby-version"
54
+ - CHANGELOG.md
55
+ - CODE_OF_CONDUCT.md
56
+ - Dockerfile
57
+ - Gemfile
58
+ - LICENSE.txt
59
+ - README.md
60
+ - Rakefile
61
+ - bin/leetcoder
62
+ - lib/leetcoder/leetcoder.rb
63
+ - lib/leetcoder/leetcoder/cli.rb
64
+ - lib/leetcoder/leetcoder/client.rb
65
+ - lib/leetcoder/leetcoder/collection.rb
66
+ - lib/leetcoder/leetcoder/commands.rb
67
+ - lib/leetcoder/leetcoder/download.rb
68
+ - lib/leetcoder/leetcoder/errors.rb
69
+ - lib/leetcoder/leetcoder/helpers/error_handler.rb
70
+ - lib/leetcoder/leetcoder/helpers/gql_queries.rb
71
+ - lib/leetcoder/leetcoder/helpers/logger.rb
72
+ - lib/leetcoder/leetcoder/helpers/utils.rb
73
+ - lib/leetcoder/leetcoder/object.rb
74
+ - lib/leetcoder/leetcoder/objects/base_object.rb
75
+ - lib/leetcoder/leetcoder/objects/question.rb
76
+ - lib/leetcoder/leetcoder/objects/submission.rb
77
+ - lib/leetcoder/leetcoder/resources/base_resource.rb
78
+ - lib/leetcoder/leetcoder/resources/questions.rb
79
+ - lib/leetcoder/leetcoder/resources/submissions.rb
80
+ - lib/leetcoder/leetcoder/version.rb
81
+ homepage: https://www.github.com/imamrb/leetcoder
82
+ licenses:
83
+ - MIT
84
+ metadata:
85
+ homepage_uri: https://www.github.com/imamrb/leetcoder
86
+ source_code_uri: https://www.github.com/imamrb/leetcoder
87
+ changelog_uri: https://www.github.com/imamrb/leetcoder/CHANGELOG.md
88
+ rubygems_mfa_required: 'false'
89
+ post_install_message:
90
+ rdoc_options: []
91
+ require_paths:
92
+ - lib
93
+ required_ruby_version: !ruby/object:Gem::Requirement
94
+ requirements:
95
+ - - ">="
96
+ - !ruby/object:Gem::Version
97
+ version: 3.1.1
98
+ required_rubygems_version: !ruby/object:Gem::Requirement
99
+ requirements:
100
+ - - ">="
101
+ - !ruby/object:Gem::Version
102
+ version: '0'
103
+ requirements: []
104
+ rubygems_version: 3.3.19
105
+ signing_key:
106
+ specification_version: 4
107
+ summary: A Ruby Leetcode Client to help you download and backup all your accepted
108
+ leetcode submissions
109
+ test_files: []