summaryrefslogtreecommitdiff
path: root/app/models/network.rb
blob: 212c2b94f80060059416f92eb960a2ae35dc4e53 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
class Network
  class UnauthorizedError < StandardError; end

  include HTTParty

  API_PREFIX = '/api/v3/'

  def authenticate(api_opts)
    opts = {
      query: api_opts
    }

    endpoint = File.join(url, API_PREFIX, 'user')
    response = self.class.get(endpoint, default_opts.merge(opts))

    build_response(response)
  end

  def projects(api_opts, scope = :owned)
    # Dont load archived projects
    api_opts.merge!(archived: false)

    opts = {
      query: api_opts
    }

    query = if scope == :owned
              'projects/owned.json'
            else
              'projects.json'
            end

    endpoint = File.join(url, API_PREFIX, query)
    response = self.class.get(endpoint, default_opts.merge(opts))

    build_response(response)
  end

  def project(api_opts, project_id)
    opts = {
      query: api_opts
    }

    query = "projects/#{project_id}.json"

    endpoint = File.join(url, API_PREFIX, query)
    response = self.class.get(endpoint, default_opts.merge(opts))

    build_response(response)
  end

  def project_hooks(api_opts, project_id)
    opts = {
      query: api_opts
    }

    query = "projects/#{project_id}/hooks.json"

    endpoint = File.join(url, API_PREFIX, query)
    response = self.class.get(endpoint, default_opts.merge(opts))

    build_response(response)
  end

  def enable_ci(project_id, data, api_opts)
    opts = {
      body: data.to_json,
      query: api_opts
    }

    query = "projects/#{project_id}/services/gitlab-ci.json"
    endpoint = File.join(url, API_PREFIX, query)
    response = self.class.put(endpoint, default_opts.merge(opts))

    case response.code
    when 200
      true
    when 401
      raise UnauthorizedError
    else
      nil
    end
  end

  def disable_ci(project_id, api_opts)
    opts = {
      query: api_opts
    }

    query = "projects/#{project_id}/services/gitlab-ci.json"

    endpoint = File.join(url, API_PREFIX, query)
    response = self.class.delete(endpoint, default_opts.merge(opts))

    build_response(response)
  end

  private

  def url
    GitlabCi.config.gitlab_server.url
  end

  def default_opts
    {
      headers: { "Content-Type" => "application/json" },
    }
  end

  def build_response(response)
    case response.code
    when 200
      response.parsed_response
    when 401
      raise UnauthorizedError
    else
      nil
    end
  end
end