aspose_cells_cloud 20.4 → 20.10

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.
Files changed (310) hide show
  1. checksums.yaml +4 -4
  2. data/lib/aspose_cells_cloud.rb +8 -1
  3. data/lib/aspose_cells_cloud/api/cells_api.rb +19867 -19164
  4. data/lib/aspose_cells_cloud/api_client.rb +489 -489
  5. data/lib/aspose_cells_cloud/api_error.rb +18 -8
  6. data/lib/aspose_cells_cloud/models/cells_cloud_file_info.rb +230 -0
  7. data/lib/aspose_cells_cloud/models/{error.rb → cells_error.rb} +1 -1
  8. data/lib/aspose_cells_cloud/models/files_upload_result.rb +1 -1
  9. data/lib/aspose_cells_cloud/models/save_result.rb +8 -26
  10. data/lib/aspose_cells_cloud/models/sparkline.rb +226 -0
  11. data/lib/aspose_cells_cloud/models/sparkline_group.rb +434 -0
  12. data/lib/aspose_cells_cloud/models/sparkline_group_response.rb +221 -0
  13. data/lib/aspose_cells_cloud/models/sparkline_groups.rb +200 -0
  14. data/lib/aspose_cells_cloud/models/sparkline_groups_response.rb +221 -0
  15. data/lib/aspose_cells_cloud/models/split_result.rb +1 -1
  16. data/lib/aspose_cells_cloud/models/text_water_marker_request.rb +239 -0
  17. data/lib/aspose_cells_cloud/version.rb +25 -25
  18. data/spec/api/cells_api_spec.rb +30 -29
  19. data/spec/api/cells_auto_filter_api_spec.rb +2 -1
  20. data/spec/api/cells_autoshapes_api_spec.rb +2 -1
  21. data/spec/api/cells_chart_area_api_spec.rb +2 -1
  22. data/spec/api/cells_charts_api_spec.rb +2 -1
  23. data/spec/api/cells_conditional_formattings_api_spec.rb +2 -1
  24. data/spec/api/cells_hypelinks_api_spec.rb +2 -1
  25. data/spec/api/cells_list_objects_api_spec.rb +2 -1
  26. data/spec/api/cells_ole_objects_api_spec.rb +5 -2
  27. data/spec/api/cells_page_breaks_api_spec.rb +4 -3
  28. data/spec/api/cells_page_setup_api_spec.rb +2 -1
  29. data/spec/api/cells_pictures_api_spec.rb +4 -2
  30. data/spec/api/cells_pivot_tables_api_spec.rb +37 -29
  31. data/spec/api/cells_properties_api_spec.rb +2 -1
  32. data/spec/api/cells_ranges_api_spec.rb +2 -1
  33. data/spec/api/cells_save_as_api_spec.rb +4 -3
  34. data/spec/api/cells_shapes_api_spec.rb +3 -2
  35. data/spec/api/cells_simple_spec.rb +2 -1
  36. data/spec/api/cells_sparkline_group_spec.rb +43 -0
  37. data/spec/api/cells_storage_api_spec.rb +69 -68
  38. data/spec/api/cells_storage_spec.rb +3 -2
  39. data/spec/api/cells_task_api_spec.rb +3 -2
  40. data/spec/api/cells_workbook_api_spec.rb +32 -29
  41. data/spec/api/cells_worksheet_validations_api_spec.rb +2 -1
  42. data/spec/api/cells_worksheets_api_spec.rb +60 -58
  43. data/spec/spec_helper.rb +4 -2
  44. metadata +31 -291
  45. data/Gemfile +0 -7
  46. data/LICENSE +0 -21
  47. data/README.md +0 -104
  48. data/Rakefile +0 -8
  49. data/aspose_cells_cloud-20.2.gem +0 -0
  50. data/aspose_cells_cloud.gemspec +0 -48
  51. data/data/Book1.xlsx +0 -0
  52. data/data/ImportData.xlsx +0 -0
  53. data/data/NewCopy.xlsx +0 -0
  54. data/data/OLEDoc.docx +0 -0
  55. data/data/PivTestFile2.xlsx +0 -0
  56. data/data/ReportData.xml +0 -1
  57. data/data/TestCase.xlsx +0 -0
  58. data/data/TestImportData.xlsx +0 -0
  59. data/data/TestImportDataCSV.csv +0 -3
  60. data/data/WaterMark.png +0 -0
  61. data/data/markdowntest.md +0 -41
  62. data/data/myDocument.xlsx +0 -0
  63. data/data/word.jpg +0 -0
  64. data/docs/AboveAverage.md +0 -10
  65. data/docs/AccessTokenResponse.md +0 -15
  66. data/docs/Area.md +0 -13
  67. data/docs/AutoFilter.md +0 -11
  68. data/docs/AutoFilterResponse.md +0 -10
  69. data/docs/AutoFitterOptions.md +0 -10
  70. data/docs/AutoShape.md +0 -42
  71. data/docs/AutoShapeResponse.md +0 -10
  72. data/docs/AutoShapes.md +0 -9
  73. data/docs/AutoShapesResponse.md +0 -10
  74. data/docs/Border.md +0 -10
  75. data/docs/CalculationOptions.md +0 -11
  76. data/docs/Cell.md +0 -24
  77. data/docs/CellArea.md +0 -11
  78. data/docs/CellResponse.md +0 -10
  79. data/docs/CellValue.md +0 -12
  80. data/docs/Cells.md +0 -14
  81. data/docs/CellsApi.md +0 -14581
  82. data/docs/CellsCloudResponse.md +0 -9
  83. data/docs/CellsColor.md +0 -12
  84. data/docs/CellsDocumentProperties.md +0 -9
  85. data/docs/CellsDocumentPropertiesResponse.md +0 -10
  86. data/docs/CellsDocumentProperty.md +0 -11
  87. data/docs/CellsDocumentPropertyResponse.md +0 -10
  88. data/docs/CellsObjectOperateTaskParameter.md +0 -10
  89. data/docs/CellsResponse.md +0 -10
  90. data/docs/Chart.md +0 -51
  91. data/docs/ChartArea.md +0 -21
  92. data/docs/ChartAreaResponse.md +0 -10
  93. data/docs/ChartFrame.md +0 -21
  94. data/docs/ChartOperateParameter.md +0 -17
  95. data/docs/Charts.md +0 -9
  96. data/docs/ChartsResponse.md +0 -10
  97. data/docs/Color.md +0 -11
  98. data/docs/ColorFilter.md +0 -12
  99. data/docs/ColorFilterRequest.md +0 -10
  100. data/docs/ColorScale.md +0 -13
  101. data/docs/Column.md +0 -13
  102. data/docs/ColumnResponse.md +0 -10
  103. data/docs/Columns.md +0 -11
  104. data/docs/ColumnsResponse.md +0 -10
  105. data/docs/Comment.md +0 -19
  106. data/docs/CommentResponse.md +0 -10
  107. data/docs/Comments.md +0 -9
  108. data/docs/CommentsResponse.md +0 -10
  109. data/docs/ConditionalFormatting.md +0 -10
  110. data/docs/ConditionalFormattingIcon.md +0 -10
  111. data/docs/ConditionalFormattingResponse.md +0 -10
  112. data/docs/ConditionalFormattingValue.md +0 -10
  113. data/docs/ConditionalFormattings.md +0 -10
  114. data/docs/ConditionalFormattingsResponse.md +0 -10
  115. data/docs/ConvertTaskParameter.md +0 -10
  116. data/docs/CopyOptions.md +0 -13
  117. data/docs/CreatePivotTableRequest.md +0 -14
  118. data/docs/CustomFilter.md +0 -9
  119. data/docs/CustomParserConfig.md +0 -10
  120. data/docs/DataBar.md +0 -19
  121. data/docs/DataBarBorder.md +0 -9
  122. data/docs/DataSorter.md +0 -11
  123. data/docs/DifSaveOptions.md +0 -15
  124. data/docs/DiscUsage.md +0 -9
  125. data/docs/DynamicFilter.md +0 -10
  126. data/docs/Error.md +0 -11
  127. data/docs/ErrorDetails.md +0 -9
  128. data/docs/FileSource.md +0 -9
  129. data/docs/FileVersion.md +0 -14
  130. data/docs/FileVersions.md +0 -8
  131. data/docs/FilesList.md +0 -8
  132. data/docs/FilesUploadResult.md +0 -9
  133. data/docs/FillFormat.md +0 -13
  134. data/docs/FillFormatResponse.md +0 -10
  135. data/docs/FilterColumn.md +0 -16
  136. data/docs/Font.md +0 -17
  137. data/docs/FontSetting.md +0 -12
  138. data/docs/FormatCondition.md +0 -22
  139. data/docs/GradientFill.md +0 -11
  140. data/docs/GradientFillStop.md +0 -10
  141. data/docs/HorizontalPageBreak.md +0 -10
  142. data/docs/HorizontalPageBreakResponse.md +0 -10
  143. data/docs/HorizontalPageBreaks.md +0 -9
  144. data/docs/HorizontalPageBreaksResponse.md +0 -10
  145. data/docs/HtmlSaveOptions.md +0 -27
  146. data/docs/Hyperlink.md +0 -12
  147. data/docs/HyperlinkResponse.md +0 -10
  148. data/docs/Hyperlinks.md +0 -10
  149. data/docs/HyperlinksResponse.md +0 -10
  150. data/docs/IconFilter.md +0 -9
  151. data/docs/IconSet.md +0 -13
  152. data/docs/ImageSaveOptions.md +0 -27
  153. data/docs/ImportBatchDataOption.md +0 -12
  154. data/docs/ImportCSVDataOption.md +0 -17
  155. data/docs/ImportDataTaskParameter.md +0 -10
  156. data/docs/ImportDoubleArrayOption.md +0 -15
  157. data/docs/ImportIntArrayOption.md +0 -15
  158. data/docs/ImportOption.md +0 -11
  159. data/docs/ImportStringArrayOption.md +0 -15
  160. data/docs/Legend.md +0 -23
  161. data/docs/LegendResponse.md +0 -10
  162. data/docs/Line.md +0 -26
  163. data/docs/LineFormat.md +0 -24
  164. data/docs/LineResponse.md +0 -10
  165. data/docs/Link.md +0 -11
  166. data/docs/LinkElement.md +0 -8
  167. data/docs/ListColumn.md +0 -9
  168. data/docs/ListObject.md +0 -23
  169. data/docs/ListObjectOperateParameter.md +0 -9
  170. data/docs/ListObjectResponse.md +0 -10
  171. data/docs/ListObjects.md +0 -9
  172. data/docs/ListObjectsResponse.md +0 -10
  173. data/docs/MHtmlSaveOptions.md +0 -27
  174. data/docs/MarkdownSaveOptions.md +0 -18
  175. data/docs/MergedCell.md +0 -12
  176. data/docs/MergedCellResponse.md +0 -10
  177. data/docs/MergedCells.md +0 -10
  178. data/docs/MergedCellsResponse.md +0 -10
  179. data/docs/MultipleFilter.md +0 -7
  180. data/docs/MultipleFilters.md +0 -9
  181. data/docs/Name.md +0 -15
  182. data/docs/NameResponse.md +0 -10
  183. data/docs/Names.md +0 -10
  184. data/docs/NamesResponse.md +0 -10
  185. data/docs/NegativeBarFormat.md +0 -11
  186. data/docs/ObjectExist.md +0 -9
  187. data/docs/OdsSaveOptions.md +0 -15
  188. data/docs/OleObject.md +0 -49
  189. data/docs/OleObjectResponse.md +0 -10
  190. data/docs/OleObjects.md +0 -9
  191. data/docs/OleObjectsResponse.md +0 -10
  192. data/docs/OoxmlSaveOptions.md +0 -16
  193. data/docs/OperateObject.md +0 -9
  194. data/docs/OperateObjectPosition.md +0 -13
  195. data/docs/OperateParameter.md +0 -8
  196. data/docs/PageBreakOperateParameter.md +0 -14
  197. data/docs/PageSection.md +0 -12
  198. data/docs/PageSectionsResponse.md +0 -10
  199. data/docs/PageSetup.md +0 -42
  200. data/docs/PageSetupOperateParameter.md +0 -9
  201. data/docs/PageSetupResponse.md +0 -10
  202. data/docs/PasswordRequest.md +0 -8
  203. data/docs/PasteOptions.md +0 -11
  204. data/docs/PatternFill.md +0 -14
  205. data/docs/PdfSaveOptions.md +0 -25
  206. data/docs/PdfSecurityOptions.md +0 -17
  207. data/docs/PicFormatOption.md +0 -13
  208. data/docs/Picture.md +0 -48
  209. data/docs/PictureResponse.md +0 -10
  210. data/docs/Pictures.md +0 -9
  211. data/docs/PicturesResponse.md +0 -10
  212. data/docs/PivotField.md +0 -46
  213. data/docs/PivotFieldResponse.md +0 -10
  214. data/docs/PivotFilter.md +0 -16
  215. data/docs/PivotFilterResponse.md +0 -10
  216. data/docs/PivotFiltersResponse.md +0 -10
  217. data/docs/PivotItem.md +0 -11
  218. data/docs/PivotTable.md +0 -76
  219. data/docs/PivotTableFieldRequest.md +0 -8
  220. data/docs/PivotTableOperateParameter.md +0 -16
  221. data/docs/PivotTableResponse.md +0 -10
  222. data/docs/PivotTables.md +0 -9
  223. data/docs/PivotTablesResponse.md +0 -10
  224. data/docs/ProtectSheetParameter.md +0 -23
  225. data/docs/Range.md +0 -16
  226. data/docs/RangeCopyRequest.md +0 -11
  227. data/docs/RangeSetOutlineBorderRequest.md +0 -11
  228. data/docs/RangeSetStyleRequest.md +0 -9
  229. data/docs/RangeValueResponse.md +0 -10
  230. data/docs/Ranges.md +0 -8
  231. data/docs/RangesResponse.md +0 -10
  232. data/docs/ResultDestination.md +0 -10
  233. data/docs/Row.md +0 -15
  234. data/docs/RowResponse.md +0 -10
  235. data/docs/Rows.md +0 -11
  236. data/docs/RowsResponse.md +0 -10
  237. data/docs/SaveOptions.md +0 -15
  238. data/docs/SaveResponse.md +0 -10
  239. data/docs/SaveResult.md +0 -10
  240. data/docs/SaveResultTaskParameter.md +0 -9
  241. data/docs/ShadowEffect.md +0 -14
  242. data/docs/Shape.md +0 -42
  243. data/docs/ShapeOperateParameter.md +0 -9
  244. data/docs/ShapeResponse.md +0 -10
  245. data/docs/Shapes.md +0 -9
  246. data/docs/ShapesResponse.md +0 -10
  247. data/docs/SingleValue.md +0 -9
  248. data/docs/SingleValueResponse.md +0 -10
  249. data/docs/SmartMarkerTaskParameter.md +0 -10
  250. data/docs/SolidFill.md +0 -10
  251. data/docs/SortKey.md +0 -10
  252. data/docs/SplitResult.md +0 -8
  253. data/docs/SplitResultDocument.md +0 -9
  254. data/docs/SplitResultResponse.md +0 -10
  255. data/docs/SplitWorkbookTaskParameter.md +0 -13
  256. data/docs/SpreadsheetML2003SaveOptions.md +0 -18
  257. data/docs/StorageExist.md +0 -8
  258. data/docs/StorageFile.md +0 -12
  259. data/docs/Style.md +0 -31
  260. data/docs/StyleResponse.md +0 -10
  261. data/docs/SvgSaveOptions.md +0 -16
  262. data/docs/TaskData.md +0 -8
  263. data/docs/TaskDescription.md +0 -9
  264. data/docs/TaskParameter.md +0 -7
  265. data/docs/TextItem.md +0 -9
  266. data/docs/TextItems.md +0 -9
  267. data/docs/TextItemsResponse.md +0 -10
  268. data/docs/TextOptions.md +0 -23
  269. data/docs/TextureFill.md +0 -13
  270. data/docs/ThemeColor.md +0 -9
  271. data/docs/TilePicOption.md +0 -13
  272. data/docs/Title.md +0 -28
  273. data/docs/TitleResponse.md +0 -10
  274. data/docs/Top10.md +0 -10
  275. data/docs/Top10Filter.md +0 -11
  276. data/docs/TxtSaveOptions.md +0 -19
  277. data/docs/Validation.md +0 -24
  278. data/docs/ValidationResponse.md +0 -10
  279. data/docs/Validations.md +0 -10
  280. data/docs/ValidationsResponse.md +0 -10
  281. data/docs/ValueType.md +0 -7
  282. data/docs/VerticalPageBreak.md +0 -10
  283. data/docs/VerticalPageBreakResponse.md +0 -10
  284. data/docs/VerticalPageBreaks.md +0 -9
  285. data/docs/VerticalPageBreaksResponse.md +0 -10
  286. data/docs/Workbook.md +0 -18
  287. data/docs/WorkbookEncryptionRequest.md +0 -10
  288. data/docs/WorkbookOperateParameter.md +0 -8
  289. data/docs/WorkbookProtectionRequest.md +0 -9
  290. data/docs/WorkbookReplaceResponse.md +0 -11
  291. data/docs/WorkbookResponse.md +0 -10
  292. data/docs/WorkbookSettings.md +0 -52
  293. data/docs/WorkbookSettingsOperateParameter.md +0 -9
  294. data/docs/WorkbookSettingsResponse.md +0 -10
  295. data/docs/Worksheet.md +0 -39
  296. data/docs/WorksheetMovingRequest.md +0 -9
  297. data/docs/WorksheetReplaceResponse.md +0 -11
  298. data/docs/WorksheetResponse.md +0 -10
  299. data/docs/Worksheets.md +0 -9
  300. data/docs/WorksheetsResponse.md +0 -10
  301. data/docs/XlsSaveOptions.md +0 -15
  302. data/docs/XlsbSaveOptions.md +0 -15
  303. data/docs/XpsSaveOptions.md +0 -15
  304. data/git_push.sh +0 -55
  305. data/lib/aspose_cells_cloud/.api_client.rb.swp +0 -0
  306. data/runTest.sh +0 -4
  307. data/spec/api/cells_one_spec.rb +0 -37
  308. data/spec/api/o_auth_api_spec.rb +0 -51
  309. data/test.pdf +0 -0
  310. data/testResult.txt +0 -113
@@ -1,489 +1,489 @@
1
- =begin
2
- --------------------------------------------------------------------------------------------------------------------
3
- Copyright (c) 2020 Aspose.Cells Cloud
4
- Permission is hereby granted, free of charge, to any person obtaining a copy
5
- of this software and associated documentation files (the "Software"), to deal
6
- in the Software without restriction, including without limitation the rights
7
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- copies of the Software, and to permit persons to whom the Software is
9
- furnished to do so, subject to the following conditions:
10
- The above copyright notice and this permission notice shall be included in all
11
- copies or substantial portions of the Software.
12
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
17
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
18
- SOFTWARE.
19
- --------------------------------------------------------------------------------------------------------------------
20
-
21
- =end
22
-
23
- require 'date'
24
- require 'json'
25
- require 'logger'
26
- require 'tempfile'
27
- require 'uri'
28
- require 'faraday'
29
- require_relative 'version'
30
- require_relative 'api_error'
31
-
32
- module AsposeCellsCloud
33
- class ApiClient
34
- # The Configuration object holding settings to be used in the API client.
35
- attr_accessor :config
36
-
37
- # Defines the headers to be used in HTTP requests of all API calls by default.
38
- #
39
- # @return [Hash]
40
- attr_accessor :default_headers
41
-
42
- attr_accessor :get_access_token_time
43
- # Initializes the ApiClient
44
- # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
45
- def initialize(config = Configuration.default)
46
- @config = config
47
-
48
- @default_headers = {
49
- 'Content-Type' => "application/json",
50
- 'x-aspose-client' => "ruby sdk",
51
- 'x-aspose-version' => "#{ AsposeCellsCloud::VERSION }"
52
- }
53
- end
54
-
55
- def self.default
56
- @@default ||= ApiClient.new
57
- end
58
-
59
- # Call an API with given options.
60
- #
61
- # @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements:
62
- # the data deserialized from response body (could be nil), response status code and response headers.
63
- def call_api(http_method, path, opts = {})
64
- response = build_request(http_method, path, opts)
65
- download_file response if opts[:return_type] == 'File'
66
-
67
- if @config.debugging
68
- @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
69
- end
70
-
71
- unless response.success?
72
-
73
- if response.status == 0
74
- # Errors from libcurl will be made visible here
75
- fail ApiError.new(:code => 0,
76
- :message => response.reason_phrase)
77
- else
78
- fail ApiError.new(:code => response.status,
79
- :response_headers => response.headers,
80
- :response_body => response.body),
81
- response.reason_phrase
82
- end
83
- end
84
-
85
- if opts[:return_type]
86
- data = deserialize(response, opts[:return_type])
87
- else
88
- data = nil
89
- end
90
- [data, response.status, response.headers]
91
- end
92
-
93
- # Builds the HTTP request
94
- #
95
- # @param [String] http_method HTTP method/verb (e.g. POST)
96
- # @param [String] path URL path (e.g. /account/new)
97
- # @option opts [Hash] :header_params Header parameters
98
- # @option opts [Hash] :query_params Query parameters
99
- # @option opts [Hash] :form_params Query parameters
100
- # @option opts [Object] :body HTTP body (JSON/XML)
101
- # @return [Faraday::Response] A Faraday Response
102
- def build_request(http_method, path, opts = {})
103
- url = build_request_url(path)
104
- http_method = http_method.to_sym.downcase
105
-
106
- header_params = @default_headers.merge(opts[:header_params] || {})
107
- query_params = opts[:query_params] || {}
108
- form_params = opts[:form_params] || {}
109
- body = opts[:body] || {}
110
-
111
- update_params_for_auth! header_params, query_params, opts[:auth_names]
112
-
113
- req_opts = {
114
- :method => http_method,
115
- :headers => header_params,
116
- :params => query_params,
117
- :body => body
118
- }
119
-
120
- if [:post, :patch, :put, :delete].include?(http_method)
121
- req_body = build_request_body(header_params, form_params, opts[:body])
122
- req_opts.update :body => req_body
123
- if @config.debugging
124
- @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
125
- end
126
- end
127
-
128
- # OAuth 2.0
129
- req_opts[:params] = opts[:query_params]
130
-
131
- add_o_auth_token(req_opts)
132
-
133
- conn = Faraday.new url, {:params => query_params, :headers => header_params} do |f|
134
- f.request :multipart
135
- f.request :url_encoded
136
- f.adapter Faraday.default_adapter
137
- end
138
-
139
- if req_opts[:body] == {}
140
- req_opts[:body] = nil
141
- end
142
-
143
- case http_method
144
- when :post
145
- return conn.post url, req_opts[:body]
146
- when :put
147
- return conn.put url, req_opts[:body]
148
- when :get
149
- return conn.get url, req_opts[:body]
150
- else
151
- return conn.delete url do |c|
152
- c.body = req_opts[:body]
153
- end
154
- end
155
- end
156
-
157
- # Check if the given MIME is a JSON MIME.
158
- # JSON MIME examples:
159
- # application/json
160
- # application/json; charset=UTF8
161
- # APPLICATION/JSON
162
- # */*
163
- # @param [String] mime MIME
164
- # @return [Boolean] True if the MIME is application/json
165
- def json_mime?(mime)
166
- (mime == "*/*") || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
167
- end
168
-
169
- # Deserialize the response to the given return type.
170
- #
171
- # @param [Response] response HTTP response
172
- # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
173
- def deserialize(response, return_type)
174
- body = response.body
175
-
176
- # handle file downloading - return the File instance processed in request callbacks
177
- # note that response body is empty when the file is written in chunks in request on_body callback
178
- return @tempfile if return_type == 'File'
179
-
180
- return nil if body.nil? || body.empty?
181
-
182
- # return response body directly for String return type
183
- return body if return_type == 'String'
184
-
185
- # ensuring a default content type
186
- content_type = response.headers['Content-Type'] || 'application/json'
187
-
188
- raise "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
189
-
190
- begin
191
- data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
192
- rescue JSON::ParserError => e
193
- if %w(String Date DateTime).include?(return_type)
194
- data = body
195
- else
196
- raise e
197
- end
198
- end
199
-
200
- convert_to_type data, return_type
201
- end
202
-
203
- # Convert data to the given return type.
204
- # @param [Object] data Data to be converted
205
- # @param [String] return_type Return type
206
- # @return [Mixed] Data in a particular type
207
- def convert_to_type(data, return_type)
208
- return nil if data.nil?
209
- case return_type
210
- when 'String'
211
- data.to_s
212
- when 'Integer'
213
- data.to_i
214
- when 'Float'
215
- data.to_f
216
- when 'BOOLEAN'
217
- data == true
218
- when 'DateTime'
219
- # parse date time (expecting ISO 8601 format)
220
- DateTime.parse data
221
- when 'Date'
222
- # parse date time (expecting ISO 8601 format)
223
- Date.parse data
224
- when 'Object'
225
- # generic object (usually a Hash), return directly
226
- data
227
- when /\AArray<(.+)>\z/
228
- # e.g. Array<Pet>
229
- sub_type = $1
230
- data.map {|item| convert_to_type(item, sub_type) }
231
- when /\AHash\<String, (.+)\>\z/
232
- # e.g. Hash<String, Integer>
233
- sub_type = $1
234
- {}.tap do |hash|
235
- data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
236
- end
237
- else
238
- # models, e.g. Pet
239
- AsposeCellsCloud.const_get(return_type).new.tap do |model|
240
- model.build_from_hash data
241
- end
242
- end
243
- end
244
-
245
- # Save response body into a file in (the defined) temporary folder, using the filename
246
- # from the "Content-Disposition" header if provided, otherwise a random filename.
247
- # The response body is written to the file in chunks in order to handle files which
248
- # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
249
- # process can use.
250
- #
251
- # @see Configuration#temp_folder_path
252
- def download_file(response)
253
- tempfile = nil
254
- encoding = nil
255
-
256
- content_disposition = response.headers['Content-Disposition']
257
- if content_disposition and content_disposition =~ /filename=/i
258
- filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
259
- prefix = sanitize_filename(filename)
260
- else
261
- prefix = 'download-'
262
- end
263
- prefix = prefix + '-' unless prefix.end_with?('-')
264
- encoding = response.body.encoding
265
- tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
266
- @tempfile = tempfile
267
-
268
- tempfile.write(response.body)
269
-
270
- response.on_complete do |resp|
271
- tempfile.close
272
- @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
273
- "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
274
- "will be deleted automatically with GC. It's also recommended to delete the temp file "\
275
- "explicitly with `tempfile.delete`"
276
- end
277
- end
278
-
279
- # Sanitize filename by removing path.
280
- # e.g. ../../sun.gif becomes sun.gif
281
- #
282
- # @param [String] filename the filename to be sanitized
283
- # @return [String] the sanitized filename
284
- def sanitize_filename(filename)
285
- filename.gsub(/.*[\/\\]/, '')
286
- end
287
-
288
- def build_request_url(path)
289
- # Add leading and trailing slashes to path
290
- path = "/#{path}".gsub(/\/+/, '/')
291
- URI.encode(@config.base_url + path)
292
- end
293
-
294
- # Builds the HTTP request body
295
- #
296
- # @param [Hash] header_params Header parameters
297
- # @param [Hash] form_params Query parameters
298
- # @param [Object] body HTTP body (JSON/XML)
299
- # @return [String] HTTP body data in the form of string
300
- def build_request_body(header_params, form_params, body)
301
- # http form
302
- if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
303
- header_params['Content-Type'] == 'multipart/form-data'
304
- data = {}
305
- form_params.each do |key, value|
306
- case value
307
- when ::File
308
- data[key] = Faraday::UploadIO.new(value.path, MimeMagic.by_magic(value).to_s, key)
309
- when ::Array, nil
310
- # let typhoeus handle File, Array and nil parameters
311
- data[key] = value
312
- else
313
- data[key] = value.to_s
314
- end
315
- end
316
- elsif body
317
- data = body.is_a?(String) ? body : body.to_json
318
- else
319
- data = nil
320
- end
321
- data
322
- end
323
-
324
- # Update hearder and query params based on authentication settings.
325
- #
326
- # @param [Hash] header_params Header parameters
327
- # @param [Hash] query_params Query parameters
328
- # @param [String] auth_names Authentication scheme name
329
- def update_params_for_auth!(header_params, query_params, auth_names)
330
- Array(auth_names).each do |auth_name|
331
- auth_setting = @config.auth_settings[auth_name]
332
- next unless auth_setting
333
- case auth_setting[:in]
334
- when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
335
- when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
336
- else raise ArgumentError, 'Authentication token must be in `query` of `header`'
337
- end
338
- end
339
- end
340
-
341
- # Sets user agent in HTTP header
342
- #
343
- # @param [String] user_agent User agent (e.g. swagger-codegen/ruby/1.0.0)
344
- def user_agent=(user_agent)
345
- @user_agent = user_agent
346
- @default_headers['User-Agent'] = @user_agent
347
- end
348
-
349
- # Return Accept header based on an array of accepts provided.
350
- # @param [Array] accepts array for Accept
351
- # @return [String] the Accept header (e.g. application/json)
352
- def select_header_accept(accepts)
353
- return nil if accepts.nil? || accepts.empty?
354
- # use JSON when present, otherwise use all of the provided
355
- json_accept = accepts.find { |s| json_mime?(s) }
356
- return json_accept || accepts.join(',')
357
- end
358
-
359
- # Return Content-Type header based on an array of content types provided.
360
- # @param [Array] content_types array for Content-Type
361
- # @return [String] the Content-Type header (e.g. application/json)
362
- def select_header_content_type(content_types)
363
- # use application/json by default
364
- return 'application/json' if content_types.nil? || content_types.empty?
365
- # use JSON when present, otherwise use the first one
366
- json_content_type = content_types.find { |s| json_mime?(s) }
367
- return json_content_type || content_types.first
368
- end
369
-
370
- # Convert object (array, hash, object, etc) to JSON string.
371
- # @param [Object] model object to be converted into JSON string
372
- # @return [String] JSON string representation of the object
373
- def object_to_http_body(model)
374
- return '"' + model + '"' if model.is_a?(String)
375
- return model if model.nil?
376
- local_body = nil
377
- if model.is_a?(Array)
378
- local_body = model.map{|m| object_to_hash(m) }
379
- else
380
- local_body = object_to_hash(model)
381
- end
382
- local_body.to_json
383
- end
384
-
385
- # Convert object(non-array) to hash.
386
- # @param [Object] obj object to be converted into JSON string
387
- # @return [String] JSON string representation of the object
388
- def object_to_hash(obj)
389
- if obj.respond_to?(:to_hash)
390
- obj.to_hash
391
- else
392
- obj
393
- end
394
- end
395
-
396
- # Build parameter value according to the given collection format.
397
- # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
398
- def build_collection_param(param, collection_format)
399
- case collection_format
400
- when :csv
401
- param.join(',')
402
- when :ssv
403
- param.join(' ')
404
- when :tsv
405
- param.join("\t")
406
- when :pipes
407
- param.join('|')
408
- when :multi
409
- # return the array directly as faraday will handle it as expected
410
- param
411
- else
412
- fail "unknown collection format: #{collection_format.inspect}"
413
- end
414
- end
415
-
416
- # Request access and refresh tokens if needed
417
- def request_token_if_needed
418
-
419
- # check token exists
420
- if @config.access_token
421
- now = Time.now
422
- time_difference = now - $get_access_token_time
423
- if time_difference < 86300
424
- return
425
- end
426
- end
427
-
428
- # resource path
429
- local_var_path = "/connect/token"
430
- if @config.api_version === "v1.1"
431
- local_var_path ="/oauth2/token"
432
- end
433
- url = build_request_url(local_var_path).gsub('/'+config.api_version, '')
434
- #url = build_request_url(local_var_path).gsub('/v3.0', '')
435
-
436
- # header parameters
437
- header_params = {}
438
- # HTTP header 'Content-Type'
439
- header_params['Content-Type'] = select_header_content_type(['application/x-www-form-urlencoded'])
440
-
441
- query_params = {}
442
- # form parameters
443
- form_params = {}
444
- form_params["grant_type"] = 'client_credentials'
445
- form_params["client_id"] = @config.app_sid
446
- form_params["client_secret"] = @config.app_key
447
-
448
- body = {}
449
-
450
-
451
- req_opts = {
452
- :headers => header_params,
453
- :params => query_params,
454
- :body => body
455
- }
456
-
457
-
458
- req_body = build_request_body(header_params, form_params, body)
459
- req_opts.update :body => req_body
460
-
461
- req_opts[:params] = query_params
462
-
463
-
464
- conn = Faraday.new url, {:params => query_params, :headers => header_params} do |f|
465
- f.request :multipart
466
- f.request :url_encoded
467
- f.adapter Faraday.default_adapter
468
- end
469
-
470
- if req_opts[:body] == {}
471
- req_opts[:body] = nil
472
- end
473
-
474
-
475
- response = conn.post url, form_params, req_opts[:body]
476
- data = JSON.parse("[#{response.body}]", :symbolize_names => true)[0]
477
-
478
- @config.access_token = data[:access_token]
479
-
480
- $get_access_token_time = Time.now
481
- end
482
-
483
- # Adds OAuth2.0 token
484
- def add_o_auth_token(req_opts)
485
- req_opts[:headers][:Authorization] = "Bearer " + @config.access_token
486
- end
487
-
488
- end
489
- end
1
+ =begin
2
+ --------------------------------------------------------------------------------------------------------------------
3
+ Copyright (c) 2020 Aspose.Cells Cloud
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ of this software and associated documentation files (the "Software"), to deal
6
+ in the Software without restriction, including without limitation the rights
7
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the Software is
9
+ furnished to do so, subject to the following conditions:
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
17
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
18
+ SOFTWARE.
19
+ --------------------------------------------------------------------------------------------------------------------
20
+
21
+ =end
22
+
23
+ require 'date'
24
+ require 'json'
25
+ require 'logger'
26
+ require 'tempfile'
27
+ require 'uri'
28
+ require 'faraday'
29
+ require_relative 'version'
30
+ require_relative 'api_error'
31
+
32
+ module AsposeCellsCloud
33
+ class ApiClient
34
+ # The Configuration object holding settings to be used in the API client.
35
+ attr_accessor :config
36
+
37
+ # Defines the headers to be used in HTTP requests of all API calls by default.
38
+ #
39
+ # @return [Hash]
40
+ attr_accessor :default_headers
41
+
42
+ attr_accessor :get_access_token_time
43
+ # Initializes the ApiClient
44
+ # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
45
+ def initialize(config = Configuration.default)
46
+ @config = config
47
+
48
+ @default_headers = {
49
+ 'Content-Type' => "application/json",
50
+ 'x-aspose-client' => "ruby sdk",
51
+ 'x-aspose-version' => "#{ AsposeCellsCloud::VERSION }"
52
+ }
53
+ end
54
+
55
+ def self.default
56
+ @@default ||= ApiClient.new
57
+ end
58
+
59
+ # Call an API with given options.
60
+ #
61
+ # @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements:
62
+ # the data deserialized from response body (could be nil), response status code and response headers.
63
+ def call_api(http_method, path, opts = {})
64
+ response = build_request(http_method, path, opts)
65
+ download_file response if opts[:return_type] == 'File'
66
+
67
+ if @config.debugging
68
+ @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
69
+ end
70
+
71
+ unless response.success?
72
+
73
+ if response.status == 0
74
+ # Errors from libcurl will be made visible here
75
+ fail ApiError.new(:code => 0,
76
+ :message => response.reason_phrase)
77
+ else
78
+ fail ApiError.new(:code => response.status,
79
+ :response_headers => response.headers,
80
+ :response_body => response.body),
81
+ response.reason_phrase
82
+ end
83
+ end
84
+
85
+ if opts[:return_type]
86
+ data = deserialize(response, opts[:return_type])
87
+ else
88
+ data = nil
89
+ end
90
+ [data, response.status, response.headers]
91
+ end
92
+
93
+ # Builds the HTTP request
94
+ #
95
+ # @param [String] http_method HTTP method/verb (e.g. POST)
96
+ # @param [String] path URL path (e.g. /account/new)
97
+ # @option opts [Hash] :header_params Header parameters
98
+ # @option opts [Hash] :query_params Query parameters
99
+ # @option opts [Hash] :form_params Query parameters
100
+ # @option opts [Object] :body HTTP body (JSON/XML)
101
+ # @return [Faraday::Response] A Faraday Response
102
+ def build_request(http_method, path, opts = {})
103
+ url = build_request_url(path)
104
+ http_method = http_method.to_sym.downcase
105
+
106
+ header_params = @default_headers.merge(opts[:header_params] || {})
107
+ query_params = opts[:query_params] || {}
108
+ form_params = opts[:form_params] || {}
109
+ body = opts[:body] || {}
110
+
111
+ update_params_for_auth! header_params, query_params, opts[:auth_names]
112
+
113
+ req_opts = {
114
+ :method => http_method,
115
+ :headers => header_params,
116
+ :params => query_params,
117
+ :body => body
118
+ }
119
+
120
+ if [:post, :patch, :put, :delete].include?(http_method)
121
+ req_body = build_request_body(header_params, form_params, opts[:body])
122
+ req_opts.update :body => req_body
123
+ if @config.debugging
124
+ @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
125
+ end
126
+ end
127
+
128
+ # OAuth 2.0
129
+ req_opts[:params] = opts[:query_params]
130
+
131
+ add_o_auth_token(req_opts)
132
+
133
+
134
+ conn = Faraday.new url, {:params => query_params, :headers => header_params} do |f|
135
+ f.request :multipart
136
+ f.request :url_encoded
137
+ f.adapter Faraday.default_adapter
138
+ end
139
+
140
+ if req_opts[:body] == {}
141
+ req_opts[:body] = nil
142
+ end
143
+
144
+ case http_method
145
+ when :post
146
+ return conn.post url, req_opts[:body]
147
+ when :put
148
+ return conn.put url, req_opts[:body]
149
+ when :get
150
+ return conn.get url, req_opts[:body]
151
+ else
152
+ return conn.delete url do |c|
153
+ c.body = req_opts[:body]
154
+ end
155
+ end
156
+ end
157
+
158
+ # Check if the given MIME is a JSON MIME.
159
+ # JSON MIME examples:
160
+ # application/json
161
+ # application/json; charset=UTF8
162
+ # APPLICATION/JSON
163
+ # */*
164
+ # @param [String] mime MIME
165
+ # @return [Boolean] True if the MIME is application/json
166
+ def json_mime?(mime)
167
+ (mime == "*/*") || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
168
+ end
169
+
170
+ # Deserialize the response to the given return type.
171
+ #
172
+ # @param [Response] response HTTP response
173
+ # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
174
+ def deserialize(response, return_type)
175
+ body = response.body
176
+
177
+ # handle file downloading - return the File instance processed in request callbacks
178
+ # note that response body is empty when the file is written in chunks in request on_body callback
179
+ return @tempfile if return_type == 'File'
180
+
181
+ return nil if body.nil? || body.empty?
182
+
183
+ # return response body directly for String return type
184
+ return body if return_type == 'String'
185
+
186
+ # ensuring a default content type
187
+ content_type = response.headers['Content-Type'] || 'application/json'
188
+
189
+ raise "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
190
+
191
+ begin
192
+ data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
193
+ rescue JSON::ParserError => e
194
+ if %w(String Date DateTime).include?(return_type)
195
+ data = body
196
+ else
197
+ raise e
198
+ end
199
+ end
200
+
201
+ convert_to_type data, return_type
202
+ end
203
+
204
+ # Convert data to the given return type.
205
+ # @param [Object] data Data to be converted
206
+ # @param [String] return_type Return type
207
+ # @return [Mixed] Data in a particular type
208
+ def convert_to_type(data, return_type)
209
+ return nil if data.nil?
210
+ case return_type
211
+ when 'String'
212
+ data.to_s
213
+ when 'Integer'
214
+ data.to_i
215
+ when 'Float'
216
+ data.to_f
217
+ when 'BOOLEAN'
218
+ data == true
219
+ when 'DateTime'
220
+ # parse date time (expecting ISO 8601 format)
221
+ DateTime.parse data
222
+ when 'Date'
223
+ # parse date time (expecting ISO 8601 format)
224
+ Date.parse data
225
+ when 'Object'
226
+ # generic object (usually a Hash), return directly
227
+ data
228
+ when /\AArray<(.+)>\z/
229
+ # e.g. Array<Pet>
230
+ sub_type = $1
231
+ data.map {|item| convert_to_type(item, sub_type) }
232
+ when /\AHash\<String, (.+)\>\z/
233
+ # e.g. Hash<String, Integer>
234
+ sub_type = $1
235
+ {}.tap do |hash|
236
+ data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
237
+ end
238
+ else
239
+ # models, e.g. Pet
240
+ AsposeCellsCloud.const_get(return_type).new.tap do |model|
241
+ model.build_from_hash data
242
+ end
243
+ end
244
+ end
245
+
246
+ # Save response body into a file in (the defined) temporary folder, using the filename
247
+ # from the "Content-Disposition" header if provided, otherwise a random filename.
248
+ # The response body is written to the file in chunks in order to handle files which
249
+ # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
250
+ # process can use.
251
+ #
252
+ # @see Configuration#temp_folder_path
253
+ def download_file(response)
254
+ tempfile = nil
255
+ encoding = nil
256
+
257
+ content_disposition = response.headers['Content-Disposition']
258
+ if content_disposition and content_disposition =~ /filename=/i
259
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
260
+ prefix = sanitize_filename(filename)
261
+ else
262
+ prefix = 'download-'
263
+ end
264
+ prefix = prefix + '-' unless prefix.end_with?('-')
265
+ encoding = response.body.encoding
266
+ tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
267
+ @tempfile = tempfile
268
+
269
+ tempfile.write(response.body)
270
+
271
+ response.on_complete do |resp|
272
+ tempfile.close
273
+ @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
274
+ "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
275
+ "will be deleted automatically with GC. It's also recommended to delete the temp file "\
276
+ "explicitly with `tempfile.delete`"
277
+ end
278
+ end
279
+
280
+ # Sanitize filename by removing path.
281
+ # e.g. ../../sun.gif becomes sun.gif
282
+ #
283
+ # @param [String] filename the filename to be sanitized
284
+ # @return [String] the sanitized filename
285
+ def sanitize_filename(filename)
286
+ filename.gsub(/.*[\/\\]/, '')
287
+ end
288
+
289
+ def build_request_url(path)
290
+ # Add leading and trailing slashes to path
291
+ path = "/#{path}".gsub(/\/+/, '/')
292
+ URI.encode(@config.base_url + path)
293
+ end
294
+
295
+ # Builds the HTTP request body
296
+ #
297
+ # @param [Hash] header_params Header parameters
298
+ # @param [Hash] form_params Query parameters
299
+ # @param [Object] body HTTP body (JSON/XML)
300
+ # @return [String] HTTP body data in the form of string
301
+ def build_request_body(header_params, form_params, body)
302
+ # http form
303
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
304
+ header_params['Content-Type'] == 'multipart/form-data'
305
+ data = {}
306
+ form_params.each do |key, value|
307
+ case value
308
+ when ::File
309
+ data[key] = Faraday::UploadIO.new(value.path, MimeMagic.by_magic(value).to_s, key)
310
+ when ::Array, nil
311
+ # let typhoeus handle File, Array and nil parameters
312
+ data[key] = value
313
+ else
314
+ data[key] = value.to_s
315
+ end
316
+ end
317
+ elsif body
318
+ data = body.is_a?(String) ? body : body.to_json
319
+ else
320
+ data = nil
321
+ end
322
+ data
323
+ end
324
+
325
+ # Update hearder and query params based on authentication settings.
326
+ #
327
+ # @param [Hash] header_params Header parameters
328
+ # @param [Hash] query_params Query parameters
329
+ # @param [String] auth_names Authentication scheme name
330
+ def update_params_for_auth!(header_params, query_params, auth_names)
331
+ Array(auth_names).each do |auth_name|
332
+ auth_setting = @config.auth_settings[auth_name]
333
+ next unless auth_setting
334
+ case auth_setting[:in]
335
+ when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
336
+ when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
337
+ else raise ArgumentError, 'Authentication token must be in `query` of `header`'
338
+ end
339
+ end
340
+ end
341
+
342
+ # Sets user agent in HTTP header
343
+ #
344
+ # @param [String] user_agent User agent (e.g. swagger-codegen/ruby/1.0.0)
345
+ def user_agent=(user_agent)
346
+ @user_agent = user_agent
347
+ @default_headers['User-Agent'] = @user_agent
348
+ end
349
+
350
+ # Return Accept header based on an array of accepts provided.
351
+ # @param [Array] accepts array for Accept
352
+ # @return [String] the Accept header (e.g. application/json)
353
+ def select_header_accept(accepts)
354
+ return nil if accepts.nil? || accepts.empty?
355
+ # use JSON when present, otherwise use all of the provided
356
+ json_accept = accepts.find { |s| json_mime?(s) }
357
+ return json_accept || accepts.join(',')
358
+ end
359
+
360
+ # Return Content-Type header based on an array of content types provided.
361
+ # @param [Array] content_types array for Content-Type
362
+ # @return [String] the Content-Type header (e.g. application/json)
363
+ def select_header_content_type(content_types)
364
+ # use application/json by default
365
+ return 'application/json' if content_types.nil? || content_types.empty?
366
+ # use JSON when present, otherwise use the first one
367
+ json_content_type = content_types.find { |s| json_mime?(s) }
368
+ return json_content_type || content_types.first
369
+ end
370
+
371
+ # Convert object (array, hash, object, etc) to JSON string.
372
+ # @param [Object] model object to be converted into JSON string
373
+ # @return [String] JSON string representation of the object
374
+ def object_to_http_body(model)
375
+ return '"' + model + '"' if model.is_a?(String)
376
+ return model if model.nil?
377
+ local_body = nil
378
+ if model.is_a?(Array)
379
+ local_body = model.map{|m| object_to_hash(m) }
380
+ else
381
+ local_body = object_to_hash(model)
382
+ end
383
+ local_body.to_json
384
+ end
385
+
386
+ # Convert object(non-array) to hash.
387
+ # @param [Object] obj object to be converted into JSON string
388
+ # @return [String] JSON string representation of the object
389
+ def object_to_hash(obj)
390
+ if obj.respond_to?(:to_hash)
391
+ obj.to_hash
392
+ else
393
+ obj
394
+ end
395
+ end
396
+
397
+ # Build parameter value according to the given collection format.
398
+ # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
399
+ def build_collection_param(param, collection_format)
400
+ case collection_format
401
+ when :csv
402
+ param.join(',')
403
+ when :ssv
404
+ param.join(' ')
405
+ when :tsv
406
+ param.join("\t")
407
+ when :pipes
408
+ param.join('|')
409
+ when :multi
410
+ # return the array directly as faraday will handle it as expected
411
+ param
412
+ else
413
+ fail "unknown collection format: #{collection_format.inspect}"
414
+ end
415
+ end
416
+
417
+ # Request access and refresh tokens if needed
418
+ def request_token_if_needed
419
+ # check token exists
420
+ if @config.access_token
421
+ now = Time.now
422
+ time_difference = now - $get_access_token_time
423
+ if time_difference < 86300
424
+ return
425
+ end
426
+ end
427
+
428
+ # resource path
429
+ local_var_path = "/connect/token"
430
+ if @config.api_version === "v1.1"
431
+ local_var_path ="/oauth2/token"
432
+ end
433
+ url = build_request_url(local_var_path).gsub('/'+config.api_version, '')
434
+ #url = build_request_url(local_var_path).gsub('/v3.0', '')
435
+
436
+ # header parameters
437
+ header_params = {}
438
+ # HTTP header 'Content-Type'
439
+ header_params['Content-Type'] = select_header_content_type(['application/x-www-form-urlencoded'])
440
+
441
+ query_params = {}
442
+ # form parameters
443
+ form_params = {}
444
+ form_params["grant_type"] = 'client_credentials'
445
+ form_params["client_id"] = @config.app_sid
446
+ form_params["client_secret"] = @config.app_key
447
+
448
+ body = {}
449
+
450
+
451
+ req_opts = {
452
+ :headers => header_params,
453
+ :params => query_params,
454
+ :body => body
455
+ }
456
+
457
+
458
+ req_body = build_request_body(header_params, form_params, body)
459
+ req_opts.update :body => req_body
460
+
461
+ req_opts[:params] = query_params
462
+
463
+
464
+ conn = Faraday.new url, {:params => query_params, :headers => header_params} do |f|
465
+ f.request :multipart
466
+ f.request :url_encoded
467
+ f.adapter Faraday.default_adapter
468
+ end
469
+
470
+ if req_opts[:body] == {}
471
+ req_opts[:body] = nil
472
+ end
473
+
474
+
475
+ response = conn.post url, form_params, req_opts[:body]
476
+ data = JSON.parse("[#{response.body}]", :symbolize_names => true)[0]
477
+
478
+ @config.access_token = data[:access_token]
479
+
480
+ $get_access_token_time = Time.now
481
+ end
482
+
483
+ # Adds OAuth2.0 token
484
+ def add_o_auth_token(req_opts)
485
+ req_opts[:headers][:Authorization] = "Bearer " + @config.access_token
486
+ end
487
+
488
+ end
489
+ end