<commit_before>require 'sinatra/base'
require 'sinatra_auth_github'
require 'sinatra/activerecord'
require 'rack/cors'

require 'emerald/api/middlewares/log_stream'
require 'emerald/api/middlewares/event_stream'
require 'emerald/api/models/github_project'
require 'emerald/api/models/github_repo'
require 'emerald/api/models/plain_project'
require 'emerald/api/models/build'
require 'emerald/api/workers/job_worker'

module Emerald
  module API
    class App < Sinatra::Base
      set :database, ENV['DATABASE_URL']
      set :database_extras, { pool: 5, timeout: 3000, encoding: 'unicode' }
      set :session_secret, ENV['SESSION_SECRET']
      enable :sessions
      enable :method_override

      set :github_options, {
        :scopes    => "user, repo, write:repo_hook",
        :secret    => ENV['GITHUB_CLIENT_SECRET'],
        :client_id => ENV['GITHUB_CLIENT_ID'],
        :callback_url => '/api/v1/auth/github/callback'
      }

      register Sinatra::ActiveRecordExtension
      register Sinatra::Auth::Github
      use LogStream
      use EventStream

      helpers do
        def request_body
          result = request.body.gets
          request.body.rewind
          result
        end

        def request_json
          content = request_body
          content ||= '{}'
          JSON.parse content, symbolize_names: true
        end
      end

      get '/api/v1/auth/active' do
        authenticate!
        { authenticated: authenticated? }.to_json
      end

      get '/api/v1/auth/github/callback' do
        puts params["error"]
        if params["error"]
          redirect "/unauthenticated"
        else
          session['warden.github.oauth']['return_to'] = '/api/v1/auth/github/after'
          authenticate!
          return_to = session.delete('return_to') || _relative_url_for('/')
          redirect return_to
        end
      end

      get '/api/v1/auth/github/after' do
        authenticate!
        redirect ENV['FRONTEND_URL']
      end

      get '/api/v1/profile' do
        authenticate!
        github_user.to_h[:attribs].to_json
      end

      get '/api/v1/github/repos' do
        authenticate!
        GithubRepo.where(github_user_id: github_user.id).map(&:serialize_json).to_json
      end

      post '/api/v1/github/repos/sync' do
        authenticate!
        repos = github_user.api.repositories(github_user.login)
        github_user.api.organizations.each do |org|
          repos += github_user.api.organization_repositories(org.login)
        end
        repos.map do |repo|
          GithubRepo.create(
            full_name: repo.full_name,
            github_repo_id: repo.id,
            github_user_id: github_user.id
          ).serialize_json
        end.to_json
      end

      post '/api/v1/github/repos/:id' do |id|
        authenticate!
        repo = github_user.api.repo(id.to_i)
        project = GithubProject.create!(github_repo_id: id, name: repo.full_name, git_url: repo.clone_url)
        project.serialize_json.to_json
      end

      post '/api/v1/projects' do
        authenticate!
        project = PlainProject.create!(name: request_json[:name], git_url: request_json[:git_url])
        project.serialize_json.to_json
      end

      get '/api/v1/projects' do
        authenticate!
        Project.all.map(&:serialize_json).to_json
      end

      get '/api/v1/projects/:project_id' do |project_id|
        authenticate!
        Project.find(project_id).serialize_json.to_json
      end

      delete '/api/v1/project/:project_id' do |project_id|
        authenticate!
        Project.find(project_id).delete!
        status 204<commit_msg>add webhook when adding github repo<commit_after>require 'sinatra/base'
require 'sinatra_auth_github'
require 'sinatra/activerecord'
require 'rack/cors'

require 'emerald/api/middlewares/log_stream'
require 'emerald/api/middlewares/event_stream'
require 'emerald/api/models/github_project'
require 'emerald/api/models/github_repo'
require 'emerald/api/models/plain_project'
require 'emerald/api/models/build'
require 'emerald/api/workers/job_worker'

module Emerald
  module API
    class App < Sinatra::Base
      set :database, ENV['DATABASE_URL']
      set :database_extras, { pool: 5, timeout: 3000, encoding: 'unicode' }
      set :session_secret, ENV['SESSION_SECRET']
      enable :sessions
      enable :method_override

      set :github_options, {
        :scopes    => "user, repo, write:repo_hook",
        :secret    => ENV['GITHUB_CLIENT_SECRET'],
        :client_id => ENV['GITHUB_CLIENT_ID'],
        :callback_url => '/api/v1/auth/github/callback'
      }

      register Sinatra::ActiveRecordExtension
      register Sinatra::Auth::Github
      use LogStream
      use EventStream

      helpers do
        def request_body
          result = request.body.gets
          request.body.rewind
          result
        end

        def request_json
          content = request_body
          content ||= '{}'
          JSON.parse content, symbolize_names: true
        end
      end

      get '/api/v1/auth/active' do
        authenticate!
        { authenticated: authenticated? }.to_json
      end

      get '/api/v1/auth/github/callback' do
        puts params["error"]
        if params["error"]
          redirect "/unauthenticated"
        else
          session['warden.github.oauth']['return_to'] = '/api/v1/auth/github/after'
          authenticate!
          return_to = session.delete('return_to') || _relative_url_for('/')
          redirect return_to
        end
      end

      get '/api/v1/auth/github/after' do
        authenticate!
        redirect ENV['FRONTEND_URL']
      end

      get '/api/v1/profile' do
        authenticate!
        github_user.to_h[:attribs].to_json
      end

      get '/api/v1/github/repos' do
        authenticate!
        GithubRepo.where(github_user_id: github_user.id).map(&:serialize_json).to_json
      end

      post '/api/v1/github/repos/sync' do
        authenticate!
        repos = github_user.api.repositories(github_user.login)
        github_user.api.organizations.each do |org|
          repos += github_user.api.organization_repositories(org.login)
        end
        repos.map do |repo|
          GithubRepo.create(
            full_name: repo.full_name,
            github_repo_id: repo.id,
            github_user_id: github_user.id
          ).serialize_json
        end.to_json
      end

      post '/api/v1/github/repos/:id' do |id|
        authenticate!
        repo = github_user.api.repo(id.to_i)
        project = GithubProject.create!(github_repo_id: id, name: repo.full_name, git_url: repo.clone_url)
        github_user.api.create_hook(
          repo.full_name,
          'web',{
            :url => "http://#{request.env['HTTP_HOST']}/api/v1/projects/#{project.id}/builds/trigger/github",
            :content_type => 'json'
          },
          {
            :events => ['push'], # possibility for pull requests add 'pull_request'
            :active => true
          }
        )
        project.serialize_json.to_json
      end

      post '/api/v1/projects' do
        authenticate!
        project = PlainProject.create!(name: request_json[:name], git_url: request_json[:git_url])
        project.serialize_json.to_json
      end

      get '/api/v1/projects' do
        authenticate!
        Project.all.map(&:serialize_json).to_json
      end

      get '/api/v1/projects/:project_id' do |project_id|
        authenticate!
        Project.find(project_id).serialize_json.to_json
      end

      delete '/api/v1/project/:project_id' do |project_id|
        authenticate!
        Project.find(project_id).delete!
        status 204
{'fraction_non_alphanumeric': 0.10683537698930341, 'fraction_numerical': 0.005609183407252805, 'mean_word_length': 2.2792985457656116, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1024315', 'n_tokens_mistral': 2481, 'n_tokens_neox': 2361, 'n_words': 437}