mirror of
https://github.com/wahyd4/ruby-sdk.git
synced 2026-08-10 05:18:37 +10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
957b537da0 | ||
|
|
4db869a53a | ||
|
|
a07b323d9d | ||
|
|
785d960ac0 | ||
|
|
e308ce1cfd | ||
|
|
1248008642 | ||
|
|
57d522ce39 | ||
|
|
c2b72befb9 | ||
|
|
2912ed9eea | ||
|
|
52057ff062 | ||
|
|
69c5eadede | ||
|
|
9969818797 | ||
|
|
44dcf0b622 | ||
|
|
6bf653f116 | ||
|
|
1b0491a2c9 | ||
|
|
f53dec3242 | ||
|
|
821d2363b3 | ||
|
|
e8fb64e7ec | ||
|
|
adb20cd815 | ||
|
|
fb9eb56bc0 | ||
|
|
813f57241d | ||
|
|
4a86397b3d | ||
|
|
fbea6bd019 | ||
|
|
ed6525a35e | ||
|
|
9d4316650d | ||
|
|
5713ad93e4 | ||
|
|
63a89b57ae | ||
|
|
65d71d12ae | ||
|
|
f1ed9a9783 | ||
|
|
5332645665 | ||
|
|
946442f782 | ||
|
|
8e4805cf68 | ||
|
|
78147d76f8 | ||
|
|
2bb0514df4 | ||
|
|
0bca27457a | ||
|
|
b21833779e | ||
|
|
a64fb3a63e | ||
|
|
0d2f2f23dd | ||
|
|
d0b4fb7412 | ||
|
|
40bf2cfbbb | ||
|
|
4e80a5ec98 | ||
|
|
4fbfdbf472 | ||
|
|
d14fe23e45 | ||
|
|
3d0578cb88 | ||
|
|
09b8921d20 | ||
|
|
7d65b22e2e | ||
|
|
8b000c0a98 | ||
|
|
f93e50c838 | ||
|
|
b8f43a1ded | ||
|
|
804fa4d5b6 | ||
|
|
0f2466d4c2 | ||
|
|
93c3cb8dea | ||
|
|
3cccf69b61 | ||
|
|
b98cec1433 | ||
|
|
a29cfe5a71 | ||
|
|
17f69da758 | ||
|
|
7280ca139a | ||
|
|
bc30779647 | ||
|
|
b6ab98b238 | ||
|
|
db62d9bcd3 | ||
|
|
089ebb2354 | ||
|
|
e97582e370 | ||
|
|
c01a43f3d9 | ||
|
|
4142c0182a | ||
|
|
3d9d50c3c5 | ||
|
|
e0c4a14e20 | ||
|
|
67c4d63a05 | ||
|
|
5ffe9daf58 | ||
|
|
a6debbec49 | ||
|
|
58dfe18328 | ||
|
|
1222559c71 | ||
|
|
31cbf3a6fd | ||
|
|
3504d39cd0 | ||
|
|
2322bbcd9c | ||
|
|
1ece11ea89 | ||
|
|
48abc7f7c1 | ||
|
|
4aca5af37e | ||
|
|
35661ebcbf | ||
|
|
c87b75d3cf | ||
|
|
328306814a | ||
|
|
e2d8a07882 | ||
|
|
8f11a43123 | ||
|
|
9d8f684eec | ||
|
|
244735a3f2 | ||
|
|
53d5f1bb4b | ||
|
|
de31e33460 | ||
|
|
01711a6fd4 | ||
|
|
5735dce6e9 | ||
|
|
788e21720b | ||
|
|
1f6e9ba47b | ||
|
|
a424c79dd6 | ||
|
|
7e66297bf9 | ||
|
|
ba91ee2377 | ||
|
|
a70b6f5313 | ||
|
|
417b717bc5 | ||
|
|
5d07bc517c | ||
|
|
ad579f402b | ||
|
|
34fc65bd99 | ||
|
|
ecbeb51339 | ||
|
|
ef0d79eb17 | ||
|
|
edc86e230e | ||
|
|
5718b720df | ||
|
|
5cc4db2231 | ||
|
|
f823ff0659 | ||
|
|
5a05fd9f8f | ||
|
|
aedb459b08 | ||
|
|
1b464029f7 | ||
|
|
1d39aeec05 | ||
|
|
efe6b50c50 | ||
|
|
544d1069e2 | ||
|
|
0ccda7cdb1 | ||
|
|
3f4c79b78f | ||
|
|
26b46859a1 | ||
|
|
1bc0476671 | ||
|
|
c91c5e4246 | ||
|
|
fe70576624 | ||
|
|
0c8a8e98e0 | ||
|
|
e2b3162f1f | ||
|
|
b99ff384ef | ||
|
|
fc5afc332a | ||
|
|
5c9169b516 | ||
|
|
fee579a5ba | ||
|
|
bc1b8acea5 | ||
|
|
11188ff682 | ||
|
|
17c961da1c | ||
|
|
476937bc60 | ||
|
|
cfad4ef53f | ||
|
|
d9ea68efa8 | ||
|
|
6aaacbe2e8 | ||
|
|
8ffee73524 | ||
|
|
fa36f09765 | ||
|
|
8173b31b18 | ||
|
|
bcb8ad7392 | ||
|
|
9539c665bb | ||
|
|
27eb25fc11 | ||
|
|
9374a451cd | ||
|
|
c49ea097b8 | ||
|
|
3753e759dd | ||
|
|
97d2c23b25 | ||
|
|
4b7c5a2574 | ||
|
|
3cae9276b2 | ||
|
|
8bd052e309 | ||
|
|
e97dc07ba3 | ||
|
|
128e6f0fd7 | ||
|
|
345fafd609 | ||
|
|
5d4785c17d | ||
|
|
2890272015 | ||
|
|
eb3461a6bb | ||
|
|
1a72e1055b | ||
|
|
cd66ce79ff | ||
|
|
ae0dbced1b | ||
|
|
8f5c6c0b0a | ||
|
|
d3ec623c3e | ||
|
|
ab81095c0c | ||
|
|
f1cb65d79a | ||
|
|
36c492b9b9 | ||
|
|
cd48eca8f6 | ||
|
|
51c719767f | ||
|
|
de61097fde | ||
|
|
3a3d026812 | ||
|
|
5e8e69a339 | ||
|
|
1a1affc3d3 | ||
|
|
cb748d8857 | ||
|
|
08f36221b7 | ||
|
|
ef9c90c7c5 | ||
|
|
3302ecde6a | ||
|
|
b0335577e5 | ||
|
|
0f3704c60f | ||
|
|
818c4bb5b3 | ||
|
|
f1461c338e | ||
|
|
67280b714e | ||
|
|
8f86e6903a | ||
|
|
47cf54069d | ||
|
|
0bb4edcade | ||
|
|
b1e6235b2e | ||
|
|
e5d2367a27 | ||
|
|
3186ba40df | ||
|
|
c5708424b9 | ||
|
|
f85ee1159b | ||
|
|
804c7609ef | ||
|
|
49ab640493 | ||
|
|
85f8e68399 | ||
|
|
7dbec75553 | ||
|
|
3299d2bd02 | ||
|
|
ec8c50383b | ||
|
|
9cc157c21d | ||
|
|
3d40d4e967 | ||
|
|
fa85e838fc | ||
|
|
38970b66e3 | ||
|
|
63ccf3f2dc | ||
|
|
5c011aa816 | ||
|
|
7b507f15c6 | ||
|
|
aab7277b50 | ||
|
|
eaed72eeaa | ||
|
|
60cc7274b1 | ||
|
|
466a4ba07e | ||
|
|
444956f161 | ||
|
|
0e4b5d00bc | ||
|
|
5d2745d148 | ||
|
|
3026a40d99 | ||
|
|
84f7cc6205 | ||
|
|
5562df4b28 | ||
|
|
70c4664e0d | ||
|
|
2096bff7a7 | ||
|
|
b0af3c1814 | ||
|
|
9bda6845a0 | ||
|
|
d9422cbcf4 | ||
|
|
38c054f24c | ||
|
|
f85c4fab41 | ||
|
|
f9bbcfeec6 | ||
|
|
e3d4a80b54 | ||
|
|
61aae133cf | ||
|
|
c3e2a3d44b | ||
|
|
06b019008a | ||
|
|
957b5d1499 | ||
|
|
5b0a561cc1 | ||
|
|
d1e60697c3 | ||
|
|
089b6bc7c6 | ||
|
|
f1edde2e54 | ||
|
|
8aca8bf33e | ||
|
|
69bb9cb913 | ||
|
|
cacdb4f926 | ||
|
|
557b75f33f | ||
|
|
2cbb175423 | ||
|
|
a8a8f63887 | ||
|
|
64cf9b5d3f | ||
|
|
1a73c39ffb | ||
|
|
864076b9ec | ||
|
|
bb6efd4e0d | ||
|
|
ef1739cb2a | ||
|
|
611837b137 | ||
|
|
000eef8870 | ||
|
|
bacf83dd3c | ||
|
|
b8ad8bd7a1 | ||
|
|
38a0877b66 | ||
|
|
241a16c40b | ||
|
|
9a5a27429d | ||
|
|
8011d6d837 | ||
|
|
2451b5b51f | ||
|
|
bd34ea428e | ||
|
|
fa40449b12 | ||
|
|
cf8a38faa0 | ||
|
|
f3dd759a5b | ||
|
|
1072b1ebab | ||
|
|
df68455eed | ||
|
|
ec58895ca7 | ||
|
|
4f9ca6e468 | ||
|
|
93a78047c1 | ||
|
|
f304a2cb67 | ||
|
|
c2a30d5a01 | ||
|
|
7432857c5a | ||
|
|
1d50e3aa54 | ||
|
|
13e1051b87 | ||
|
|
7c1fd4d207 | ||
|
|
7b628281d3 | ||
|
|
263ea64367 | ||
|
|
2dfd3da781 | ||
|
|
1af173d04f | ||
|
|
b176c7a604 | ||
|
|
9c719cc8e5 | ||
|
|
e8a1343328 | ||
|
|
88b56daabd | ||
|
|
bab0f4a602 | ||
|
|
1b9077a7dd | ||
|
|
64ddbbe831 | ||
|
|
36d5fc0684 | ||
|
|
490f359a17 | ||
|
|
01bd208627 | ||
|
|
d0c69c2255 | ||
|
|
7e4aff00a1 | ||
|
|
93ca5c5009 | ||
|
|
46144f145c | ||
|
|
b2ddd186aa | ||
|
|
9f07e8d236 | ||
|
|
4f04812b5c | ||
|
|
fcc6870f2e | ||
|
|
2bd158c1fe | ||
|
|
556210548b | ||
|
|
3b58147e70 | ||
|
|
6746a8eeeb | ||
|
|
da0d8d5ef8 | ||
|
|
1a950e8f85 | ||
|
|
d1b3f3c080 | ||
|
|
46eb6e3d58 | ||
|
|
8e86a92080 | ||
|
|
33447b0d5f | ||
|
|
e7f64fabae | ||
|
|
1d63970688 | ||
|
|
83475e594a | ||
|
|
9210c7fc32 | ||
|
|
1a9dfeb9a7 | ||
|
|
da3bdd362e | ||
|
|
2bbcfff82f | ||
|
|
b2b5b8b92d | ||
|
|
e5c57d4d72 | ||
|
|
9ff7228a8f | ||
|
|
abadfe65ba | ||
|
|
006df109a7 | ||
|
|
c4b23a4d89 | ||
|
|
02d25bf63b | ||
|
|
28d4aa7743 | ||
|
|
25fd1777f6 | ||
|
|
7df449cc73 | ||
|
|
3765e72c8a | ||
|
|
84157d35fa | ||
|
|
4a83010548 | ||
|
|
313e368602 | ||
|
|
dddbf793e5 | ||
|
|
28c71771e4 | ||
|
|
d92dc24416 | ||
|
|
1eb43cb00f | ||
|
|
b2f496551b | ||
|
|
07a01834d6 | ||
|
|
c60cc6e4b8 | ||
|
|
0a4f8c1471 | ||
|
|
9719aae614 | ||
|
|
f8c3f93d29 | ||
|
|
971fa3e92b | ||
|
|
70d6d55e0c | ||
|
|
8e90310b9c | ||
|
|
8cf75eecbd | ||
|
|
ccd46828c6 | ||
|
|
2cc53fabdd | ||
|
|
7eb27d0deb | ||
|
|
b0b568d0c7 | ||
|
|
cffec32884 |
@@ -16,3 +16,4 @@ spec/reports
|
||||
test/tmp
|
||||
test/version_tmp
|
||||
tmp
|
||||
.idea
|
||||
|
||||
+8
-8
@@ -1,12 +1,12 @@
|
||||
language: ruby
|
||||
rvm:
|
||||
- 1.8.7
|
||||
- 1.9.2
|
||||
- 1.9.3
|
||||
- jruby-18mode
|
||||
- 2.0.0
|
||||
- 2.1.1
|
||||
- jruby-19mode
|
||||
- rbx-18mode
|
||||
- rbx-19mode
|
||||
- ruby-head
|
||||
- jruby-head
|
||||
- ree
|
||||
before_script:
|
||||
- export QINIU_ACCESS_KEY=QWYn5TFQsLLU1pL5MFEmX3s5DmHdUThav9WyOWOm
|
||||
- export QINIU_SECRET_KEY=Bxckh6FA-Fbs9Yt3i3cbKVK22UPBmAOHJcL95pGz
|
||||
gemfile:
|
||||
- Gemfile
|
||||
- rails3/Gemfile
|
||||
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
## CHANGE LOG
|
||||
|
||||
### V6.5.1
|
||||
|
||||
- 为 Qiniu::Auth 添加验证七牛回调请求签名合法性的函数。[https://github.com/qiniu/ruby-sdk/pull/133](https://github.com/qiniu/ruby-sdk/pull/133)
|
||||
|
||||
### v6.5.0
|
||||
|
||||
- 为 Qiniu::Auth 添加一个异常处理逻辑,在 Access Key 和 Secret Key 未正常设置(nil 值)的情况下给出正确提示。[https://github.com/qiniu/ruby-sdk/pull/126](https://github.com/qiniu/ruby-sdk/pull/126)
|
||||
|
||||
### v6.4.2
|
||||
|
||||
- gem 兼容性调整 。 [https://github.com/qiniu/ruby-sdk/pull/122](https://github.com/qiniu/ruby-sdk/pull/122)
|
||||
|
||||
- 上传策略参数调整 。 [https://github.com/qiniu/ruby-sdk/pull/120](https://github.com/qiniu/ruby-sdk/pull/120)
|
||||
|
||||
### v6.4.1
|
||||
|
||||
- 将 mime-types 的依赖版本升级到 2.4.3 。 [https://github.com/qiniu/ruby-sdk/pull/113](https://github.com/qiniu/ruby-sdk/pull/113)
|
||||
|
||||
### v6.4.0
|
||||
|
||||
- 为 put_with_put_policy() 添加 opts 参数,允许使用 :content_type 键指定上传文件的 mime type。 [https://github.com/qiniu/ruby-sdk/pull/111](https://github.com/qiniu/ruby-sdk/pull/111)
|
||||
|
||||
### v6.3.2
|
||||
|
||||
- 调整上传host。 [https://github.com/qiniu/ruby-sdk/pull/103](https://github.com/qiniu/ruby-sdk/pull/103)
|
||||
|
||||
### v6.3.1
|
||||
|
||||
- 为过期方法添加说明。 [https://github.com/qiniu/ruby-sdk/pull/98](https://github.com/qiniu/ruby-sdk/pull/98)
|
||||
- 修改上传域名。 [https://github.com/qiniu/ruby-sdk/pull/99](https://github.com/qiniu/ruby-sdk/pull/99)
|
||||
- 增加pfop参数。 [https://github.com/qiniu/ruby-sdk/pull/100](https://github.com/qiniu/ruby-sdk/pull/100)
|
||||
|
||||
### v6.3.0
|
||||
|
||||
- 添加 authorize_download_url_2 方法,对包含中文或其它 utf-8 字符的 Key 做下载授权。 [https://github.com/qiniu/ruby-sdk/pull/95](https://github.com/qiniu/ruby-sdk/pull/95)
|
||||
|
||||
### v6.2.4
|
||||
|
||||
- 调整User Agent。 [https://github.com/qiniu/ruby-sdk/pull/94](https://github.com/qiniu/ruby-sdk/pull/94)
|
||||
|
||||
### v6.2.3
|
||||
|
||||
- 为上传策略添加`persistentPipeline`参数,用于指明使用哪个命名转码队列。 [https://github.com/qiniu/ruby-sdk/pull/93](https://github.com/qiniu/ruby-sdk/pull/93)
|
||||
|
||||
### v6.2.2
|
||||
|
||||
- 为/pfop接口添加`pipeline`参数,用于指明使用哪个命名转码队列。 [https://github.com/qiniu/ruby-sdk/pull/92](https://github.com/qiniu/ruby-sdk/pull/92)
|
||||
- 为authorize_download_url()添加`:fop`参数,用于生成含数据处理指令的授权下载URL。
|
||||
|
||||
### v6.2.1
|
||||
|
||||
- 去除已废弃的publish/unpublish接口。 [https://github.com/qiniu/ruby-sdk/pull/90](https://github.com/qiniu/ruby-sdk/pull/90) (#8143)
|
||||
|
||||
### v6.2.0
|
||||
|
||||
- 重写与授权相关的函数并归入Qiniu::Auth空间,原授权凭证生成类维持不变。
|
||||
|
||||
- 添加Qiniu::Storage::PutPolicy类和Qiniu::Storage#upload_with_put_policy方法,并推荐使用两者组合实现单文件上传。
|
||||
|
||||
### v6.1.0
|
||||
|
||||
- Qiniu::Storage所有上传接口返回第三个值raw_headers,类型为Hash,包含已解析的HTTP响应报文中的所有Header信息。
|
||||
|
||||
该返回值主要用于调试。当遇到难以理解或解释的错误时,请将其中的X-Log和X-Reqid两项信息[通过邮件反馈](mailto:support@qiniu.com?subject=Ruby-SDK-Bug-Report)给我们。
|
||||
|
||||
- 更新Qiniu::Storage所有上传接口的测试用例,打印HTTP响应Header信息。
|
||||
|
||||
- 删除过时的Qiniu::Storage#put_file方法和相关测试用例。
|
||||
|
||||
该方法调用的API已过时并逐步废弃,建议用户尽快迁移到Qiniu::Storage#upload_with_token_2方法上。
|
||||
|
||||
### v6.0.1
|
||||
|
||||
- 重新划分命名空间,存储相关归入Qiniu::Storage,数据处理相关归入Qiniu::Fop,杂项相关归入Qiniu::Misc。
|
||||
|
||||
### v3.4.6
|
||||
|
||||
- `Qiniu::RS.generate_download_token()` 方法的 `:pattern` 调整为必选项。
|
||||
|
||||
### v3.4.5
|
||||
|
||||
- `Qiniu::RS.generate_upload_token()` 方法新增 `:callback_body` 和 `return_url` 选项。
|
||||
- 选项含义参考: <http://developer.qiniu.com/docs/v6/api/reference/security/put-policy.html#put-policy-callback-body>
|
||||
|
||||
### v3.4.2
|
||||
|
||||
- `Qiniu::RS.generate_upload_token()` 方法新增 `:return_body` 选项。
|
||||
|
||||
该选项(`:return_body`)可设置文件上传成功后,执行七牛云存储规定的回调API,并以 JSON 响应格式返回其执行结果。参考 [uploadToken 之 returnBody 说明](http://developer.qiniu.com/docs/v6/api/reference/security/put-policy.html#put-policy-return-body)。
|
||||
|
||||
### v3.4.1
|
||||
|
||||
增加为上传文件进行预转的选项,参见 [uploadToken 之 asyncOps 说明](http://docs.qiniu.com/api/v6/put.html#uploadToken-asyncOps)
|
||||
|
||||
- `Qiniu::RS.generate_upload_token()` 方法新增 `:async_options` 选项用于进行预转操作。
|
||||
|
||||
### v3.4.0
|
||||
|
||||
增加文件复制/移动方法,包括批量复制/移动文件
|
||||
|
||||
- `Qiniu::RS.copy(source_bucket, source_key, target_bucket, target_key)`
|
||||
- `Qiniu::RS.move(source_bucket, source_key, target_bucket, target_key)`
|
||||
- `Qiniu::RS.batch_copy [source_bucket, source_key, target_bucket, target_key], ...`
|
||||
- `Qiniu::RS.batch_move [source_bucket, source_key, target_bucket, target_key], ...`
|
||||
|
||||
### v3.3.1
|
||||
|
||||
确保单元测试里边用到的测试 Bucket 全局唯一
|
||||
|
||||
使得10多种不通的 Ruby 宿主环境能隔离互不影响地执行单元/集成测试
|
||||
|
||||
Ruby 宿主环境如下
|
||||
|
||||
1.8.7, 1.9.2, 1.9.3, jruby-18mode, jruby-19mode, rbx-18mode, rbx-19mode, ruby-head, jruby-head, ree
|
||||
|
||||
详见 <https://travis-ci.org/qiniu/ruby-sdk>
|
||||
|
||||
### v3.3.0
|
||||
|
||||
私有资源下载新版实现,添加 Qiniu::RS.generate_download_token() 方法。参考 [downloadToken](http://developer.qiniu.com/docs/v6/api/reference/security/download-token.html)
|
||||
|
||||
详见 [Ruby SDK 使用文档之私有资源下载](http://developer.qiniu.com/docs/v6/api/overview/dn/security.html)
|
||||
|
||||
### v3.2.2
|
||||
|
||||
fixed E701 error
|
||||
|
||||
断点续上传根据 mkblk 返回的 host 字段进行 bput 和 mkfile ,规避由于DNS智能解析造成的分布式并行块上传会出现上下文不连贯导致的 E701 问题。
|
||||
|
||||
### v3.2.1
|
||||
|
||||
allow images uploaded auto-orient.
|
||||
|
||||
允许图片上传成功后自动旋转。
|
||||
|
||||
参考:
|
||||
|
||||
1. [[API] multipart/form-data 上传文件之 action 字段详解](http://docs.qiniutek.com/v3/api/io/#upload-action)
|
||||
2. [[SDK] Qiniu::RS.upload_file() 方法中的参数增加了 :rotate 选项](http://docs.qiniutek.com/v3/sdk/ruby/#upload-server-side)
|
||||
|
||||
### v3.2.0
|
||||
|
||||
2012-11-06
|
||||
|
||||
allow files uploaded auto callback some APIs (like imageInfo, exif, etc…), and add those APIs callback results as part of the custom data for POST biz-server.
|
||||
|
||||
允许上传文件(图片)成功后执行回调指定的 API (比如 imageInfo, exif 接口等),并将指定API的回调结果一并 POST 发送给客户方的业务服务器。
|
||||
|
||||
参考:
|
||||
|
||||
1. [[API] 生成上传授权凭证 uploadToken 之 escape 参数详解](http://docs.qiniutek.com/v3/api/io/#escape-expression)
|
||||
2. [[SDK] Qiniu::RS.generate_upload_token() 方法中的参数增加了 :escape 选项](http://docs.qiniutek.com/v3/sdk/ruby/#generate-upload-token)
|
||||
@@ -1,7 +1,7 @@
|
||||
source 'http://ruby.taobao.org'
|
||||
source 'https://rubygems.org'
|
||||
|
||||
# Specify your gem's dependencies in qiniu-s3.gemspec
|
||||
gemspec
|
||||
# Specify your gem's dependencies in qiniu.gemspec
|
||||
gemspec :name => 'qiniu'
|
||||
|
||||
# platforms :jruby do
|
||||
# gem "jruby-openssl"
|
||||
|
||||
+34
-22
@@ -1,35 +1,47 @@
|
||||
PATH
|
||||
remote: .
|
||||
specs:
|
||||
qiniu-rs (1.1.0)
|
||||
json
|
||||
mime-types
|
||||
rest-client
|
||||
qiniu (6.5.1)
|
||||
json (~> 1.8)
|
||||
mime-types (~> 2.4.3)
|
||||
rest-client (~> 1.7.3)
|
||||
ruby-hmac (~> 0.4)
|
||||
|
||||
GEM
|
||||
remote: https://rubygems.org/
|
||||
specs:
|
||||
diff-lcs (1.1.3)
|
||||
diff-lcs (1.2.5)
|
||||
fakeweb (1.3.0)
|
||||
json (1.7.3)
|
||||
mime-types (1.18)
|
||||
rake (0.9.2.2)
|
||||
rest-client (1.6.7)
|
||||
mime-types (>= 1.16)
|
||||
rspec (2.10.0)
|
||||
rspec-core (~> 2.10.0)
|
||||
rspec-expectations (~> 2.10.0)
|
||||
rspec-mocks (~> 2.10.0)
|
||||
rspec-core (2.10.1)
|
||||
rspec-expectations (2.10.0)
|
||||
diff-lcs (~> 1.1.3)
|
||||
rspec-mocks (2.10.1)
|
||||
json (1.8.3)
|
||||
mime-types (2.4.3)
|
||||
netrc (0.11.0)
|
||||
rake (10.4.2)
|
||||
rest-client (1.7.3)
|
||||
mime-types (>= 1.16, < 3.0)
|
||||
netrc (~> 0.7)
|
||||
rspec (3.2.0)
|
||||
rspec-core (~> 3.2.0)
|
||||
rspec-expectations (~> 3.2.0)
|
||||
rspec-mocks (~> 3.2.0)
|
||||
rspec-core (3.2.2)
|
||||
rspec-support (~> 3.2.0)
|
||||
rspec-expectations (3.2.0)
|
||||
diff-lcs (>= 1.2.0, < 2.0)
|
||||
rspec-support (~> 3.2.0)
|
||||
rspec-mocks (3.2.1)
|
||||
diff-lcs (>= 1.2.0, < 2.0)
|
||||
rspec-support (~> 3.2.0)
|
||||
rspec-support (3.2.2)
|
||||
ruby-hmac (0.4.0)
|
||||
|
||||
PLATFORMS
|
||||
ruby
|
||||
|
||||
DEPENDENCIES
|
||||
fakeweb
|
||||
qiniu-rs!
|
||||
rake
|
||||
rspec
|
||||
fakeweb (~> 1.3)
|
||||
qiniu!
|
||||
rake (>= 0.9)
|
||||
rspec (>= 2.11)
|
||||
|
||||
BUNDLED WITH
|
||||
1.11.2
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Copyright (c) 2012 why404
|
||||
Copyright (c) 2012-2013 qiniutek.com
|
||||
|
||||
MIT License
|
||||
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
# Qiniu Resource (Cloud) Storage SDK for Ruby - [](http://travis-ci.org/why404/qiniu-rs) [](https://gemnasium.com/why404/qiniu-rs)
|
||||
# Qiniu Resource (Cloud) Storage SDK for Ruby
|
||||
|
||||
# 关于
|
||||
## 关于
|
||||
|
||||
此 Ruby SDK 适用于 Ruby 1.8.x, 1.9.x, jruby, rbx, ree 版本,基于 [七牛云存储官方API](http://docs.qiniutek.com/v1/api/) 构建。使用此 SDK 构建您的网络应用程序,能让您以非常便捷地方式将数据安全地存储到七牛云存储上。无论您的网络应用是一个网站程序,还是包括从云端(服务端程序)到终端(手持设备应用)的架构的服务或应用,通过七牛云存储及其 SDK,都能让您应用程序的终端用户高速上传和下载,同时也让您的服务端更加轻盈。
|
||||
此 Ruby SDK 适用于 Ruby 1.9.x, 2.0.x, 2.1.x, jruby版本,基于 [七牛云存储官方API](http://developer.qiniu.com/docs/v6/index.html) 构建。使用此 SDK 构建您的网络应用程序,能让您以非常便捷地方式将数据安全地存储到七牛云存储上。无论您的网络应用是一个网站程序,还是包括从云端(服务端程序)到终端(手持设备应用)的架构的服务或应用,通过七牛云存储及其 SDK,都能让您应用程序的终端用户高速上传和下载,同时也让您的服务端更加轻盈。
|
||||
|
||||
## 状态
|
||||
|
||||
[](https://travis-ci.org/qiniu/ruby-sdk)
|
||||
[](http://badge.fury.io/rb/qiniu)
|
||||
[](https://gemnasium.com/qiniu/ruby-sdk)
|
||||
[](https://codeclimate.com/github/qiniu/ruby-sdk)
|
||||
|
||||
## 安装
|
||||
|
||||
在您 Ruby 应用程序的 `Gemfile` 文件中,添加如下一行代码:
|
||||
|
||||
gem 'qiniu-rs'
|
||||
gem 'qiniu', '~> 6.4.1'
|
||||
|
||||
然后,在应用程序所在的目录下,可以运行 `bundle` 安装依赖包:
|
||||
|
||||
@@ -16,11 +23,11 @@
|
||||
|
||||
或者,可以使用 Ruby 的包管理器 `gem` 进行安装:
|
||||
|
||||
$ gem install qiniu-rs
|
||||
$ gem install qiniu
|
||||
|
||||
## 使用
|
||||
|
||||
参考文档:[七牛云存储 Ruby SDK 使用指南](http://docs.qiniutek.com/v2/sdk/ruby/)
|
||||
参考文档:[七牛云存储 Ruby SDK 使用指南](http://developer.qiniu.com/docs/v6/sdk/ruby-sdk.html)
|
||||
|
||||
## 贡献代码
|
||||
|
||||
@@ -32,7 +39,7 @@
|
||||
|
||||
## 许可证
|
||||
|
||||
Copyright (c) 2012 why404
|
||||
Copyright (c) 2012-2014 qiniu.com
|
||||
|
||||
基于 MIT 协议发布:
|
||||
|
||||
|
||||
+790
@@ -0,0 +1,790 @@
|
||||
---
|
||||
title: Ruby SDK
|
||||
---
|
||||
|
||||
此 Ruby SDK 适用于 Ruby 1.8.x, 1.9.x, jruby, rbx, ree 版本,基于 [七牛云存储官方API](http://docs.qiniu.com/) 构建。使用此 SDK 构建您的网络应用程序,能让您以非常便捷地方式将数据安全地存储到七牛云存储上。无论您的网络应用是一个网站程序,还是包括从云端(服务端程序)到终端(手持设备应用)的架构的服务或应用,通过七牛云存储及其 SDK,都能让您应用程序的终端用户高速上传和下载,同时也让您的服务端更加轻盈。
|
||||
|
||||
七牛云存储 Ruby SDK 源码地址:<https://github.com/qiniu/ruby-sdk>
|
||||
|
||||
**目录**
|
||||
|
||||
- [安装](#Installation)
|
||||
- [接入](#turn-on)
|
||||
- [配置密钥(AccessKey / SecretKey)](#establish_connection!)
|
||||
- [针对 Ruby On Rails 网站应用初始化设置](#ror-init)
|
||||
- [使用](#Usage)
|
||||
- [文件上传](#upload)
|
||||
- [生成上传授权凭证(uploadToken)](#generate-upload-token)
|
||||
- [Ruby 服务端上传文件](#upload-server-side)
|
||||
- [开启断点续上传](#resumable-upload)
|
||||
- [iOS / Android / Web 端直传文件说明](#upload-client-side)
|
||||
- [文件下载](#download)
|
||||
- [公有资源下载](#download-public-files)
|
||||
- [私有资源下载](#download-private-files)
|
||||
- [生成下载授权凭证(downloadToken)](#download-token)
|
||||
- [高级特性](#other-download-features)
|
||||
- [断点续下载](#resumable-download)
|
||||
- [自定义 404 NotFound](#upload-file-for-not-found)
|
||||
- [文件管理](#file-management)
|
||||
- [查看单个文件属性信息](#stat)
|
||||
- [复制单个文件](#copy)
|
||||
- [移动单个文件](#move)
|
||||
- [删除单个文件](#delete)
|
||||
- [批量操作](#batch)
|
||||
- [批量获取文件属性信息](#batch-get)
|
||||
- [批量复制文件](#batch-copy)
|
||||
- [批量移动文件](#batch-move)
|
||||
- [批量删除文件](#batch-delete)
|
||||
- [云处理](#cloud-processing)
|
||||
- [图像](#image-processing)
|
||||
- [查看图片属性信息](#image-info)
|
||||
- [查看图片EXIF信息](#image-exif)
|
||||
- [图像在线处理(缩略、裁剪、旋转、转化)](#image-mogrify-for-preview)
|
||||
- [图像在线处理(缩略、裁剪、旋转、转化)后并持久化存储](#image-mogrify-for-save-as)
|
||||
- 音频(TODO)
|
||||
- 视频(TODO)
|
||||
- [贡献代码](#Contributing)
|
||||
- [许可证](#License)
|
||||
|
||||
|
||||
<a name="Installation"></a>
|
||||
|
||||
## 安装
|
||||
|
||||
在您 Ruby 应用程序的 `Gemfile` 文件中,添加如下一行代码:
|
||||
|
||||
gem 'qiniu-rs'
|
||||
|
||||
然后,在应用程序所在的目录下,可以运行 `bundle` 安装依赖包:
|
||||
|
||||
$ bundle
|
||||
|
||||
或者,可以使用 Ruby 的包管理器 `gem` 进行安装:
|
||||
|
||||
$ gem install qiniu-rs
|
||||
|
||||
|
||||
<a name="turn-on"></a>
|
||||
|
||||
## 接入
|
||||
|
||||
<a name="establish_connection!"></a>
|
||||
|
||||
### 配置密钥(AccessKey / SecretKey)
|
||||
|
||||
要接入七牛云存储,您需要拥有一对有效的 Access Key 和 Secret Key 用来进行签名认证。可以通过如下步骤获得:
|
||||
|
||||
1. [开通七牛开发者帐号](https://portal.qiniu.com/signup)
|
||||
2. [登录七牛开发者自助平台,查看 Access Key 和 Secret Key](https://portal.qiniu.com/setting/key)
|
||||
|
||||
在获取到 Access Key 和 Secret Key 之后,您可以在您的程序中调用如下两行代码进行初始化对接:
|
||||
|
||||
Qiniu::RS.establish_connection! :access_key => YOUR_APP_ACCESS_KEY,
|
||||
:secret_key => YOUR_APP_SECRET_KEY
|
||||
|
||||
<a name="ror-init"></a>
|
||||
|
||||
### 针对 Ruby On Rails 网站应用初始化设置
|
||||
|
||||
如果您使用的是 [Ruby on Rails](http://rubyonrails.org/) 框架,我们建议您在应用初始化启动的过程中,依次调用上述两个函数即可,操作如下:
|
||||
|
||||
首先,在应用初始化脚本加载的目录中新建一个文件:`YOUR_RAILS_APP/config/initializers/qiniu-rs.rb`
|
||||
|
||||
然后,编辑 `YOUR_RAILS_APP/config/initializers/qiniu-rs.rb` 文件内容如下:
|
||||
|
||||
Qiniu::RS.establish_connection! :access_key => YOUR_APP_ACCESS_KEY,
|
||||
:secret_key => YOUR_APP_SECRET_KEY
|
||||
|
||||
这样,您就可以在您的 `RAILS_APP` 中使用七牛云存储 Ruby SDK 提供的其他任意方法了。
|
||||
|
||||
接下来,我们会逐一介绍此 SDK 提供的其他方法。
|
||||
|
||||
|
||||
<a name="Usage"></a>
|
||||
|
||||
## 使用
|
||||
|
||||
<a name="upload"></a>
|
||||
|
||||
### 文件上传
|
||||
|
||||
**注意**:如果您只是想要上传已存在您电脑本地或者是服务器上的文件到七牛云存储,可以直接使用七牛提供的 [qrsync](http://docs.qiniu.com/tools/qrsync.html) 上传工具。如果是需要通过您的网站或是移动应用(App)上传文件,则可以接入使用此 SDK,详情参考如下文档说明。
|
||||
|
||||
<a name="generate-upload-token"></a>
|
||||
|
||||
#### 生成上传授权凭证(uploadToken)
|
||||
|
||||
要上传一个文件,首先需要调用 SDK 提供的 `Qiniu::RS.generate_upload_token` 函数来获取一个经过授权用于临时匿名上传的 `upload_token`——经过数字签名的一组数据信息,该 `upload_token` 作为文件上传流中 `multipart/form-data` 的一部分进行传输。
|
||||
|
||||
`Qiniu::RS.generate_upload_token` 函数原型如下:
|
||||
|
||||
Qiniu::RS.generate_upload_token :scope => target_bucket,
|
||||
:expires_in => expires_in_seconds,
|
||||
:callback_url => callback_url,
|
||||
:callback_body => callback_body,
|
||||
:callback_body_type => callback_body_type,
|
||||
:customer => end_user_id,
|
||||
:escape => allow_upload_callback_api,
|
||||
:async_options => async_callback_api_commands,
|
||||
:return_body => custom_response_body
|
||||
|
||||
**参数**
|
||||
|
||||
:scope
|
||||
: 必须,字符串类型(String),设定文件要上传到的目标 `bucket`
|
||||
|
||||
:expires_in
|
||||
: 可选,数字类型,用于设置上传 URL 的有效期,单位:秒,缺省为 3600 秒,即 1 小时后该上传链接不再有效(但该上传URL在其生成之后的59分59秒都是可用的)。
|
||||
|
||||
:callback_url
|
||||
: 可选,字符串类型(String),用于设置文件上传成功后,七牛云存储服务端要回调客户方的业务服务器地址。
|
||||
|
||||
:callback_body
|
||||
: 可选,字符串类型(String),用于设置文件上传成功后,七牛云存储服务端向客户方的业务服务器发送回调请求的值。
|
||||
|
||||
:callback_body_type
|
||||
: 可选,字符串类型(String),用于设置文件上传成功后,七牛云存储服务端向客户方的业务服务器发送回调请求的 `Content-Type`。
|
||||
|
||||
:customer
|
||||
: 可选,字符串类型(String),客户方终端用户(End User)的ID,该字段可以用来标示一个文件的属主,这在一些特殊场景下(比如给终端用户上传的图片打上名字水印)非常有用。
|
||||
|
||||
:escape
|
||||
: 可选,数字类型,可选值 0 或者 1,缺省为 0 。值为 1 表示 callback 传递的自定义数据中允许存在转义符号 `$(VarExpression)`,参考 [VarExpression](http://docs.qiniutek.com/v3/api/words/#VarExpression)。
|
||||
|
||||
当 `escape` 的值为 `1` 时,常见的转义语法如下:
|
||||
|
||||
- 若 `callbackBodyType` 为 `application/json` 时,一个典型的自定义回调数据([CallbackParams](http://docs.qiniutek.com/v3/api/io/#CallbackParams))为:
|
||||
|
||||
`{foo: "bar", w: $(imageInfo.width), h: $(imageInfo.height), exif: $(exif)}`
|
||||
|
||||
- 若 `callbackBodyType` 为 `application/x-www-form-urlencoded` 时,一个典型的自定义回调数据([CallbackParams](http://docs.qiniutek.com/v3/api/io/#CallbackParams))为:
|
||||
|
||||
`foo=bar&w=$(imageInfo.width)&h=$(imageInfo.height)&exif=$(exif)`
|
||||
|
||||
:async_options
|
||||
: 可选,字符串类型(String),用于设置文件上传成功后,执行指定的预转指令。参考 [uploadToken 之 asyncOps 说明](http://docs.qiniutek.com/v3/api/io/#uploadToken-asyncOps)
|
||||
|
||||
:return_body
|
||||
: 可选,字符串类型(String),用于设置文件上传成功后,执行七牛云存储规定的回调API,并以 JSON 响应格式返回其执行结果。参考 [uploadToken 之 returnBody 说明](http://docs.qiniutek.com/v3/api/io/#uploadToken-returnBody)。
|
||||
|
||||
|
||||
**返回值**
|
||||
|
||||
返回一个字符串类型(String)的用于上传文件用的临时授权 `upload_token`。
|
||||
|
||||
<a name="upload-server-side"></a>
|
||||
|
||||
#### Ruby 服务端上传文件
|
||||
|
||||
通过 `Qiniu::RS.upload_file()` 方法可在客户方的业务服务器上直接往七牛云存储上传文件。该函数规格如下:
|
||||
|
||||
Qiniu::RS.upload_file :uptoken => upload_token,
|
||||
:file => file_path,
|
||||
:bucket => bucket_name,
|
||||
:key => record_id,
|
||||
:mime_type => file_mime_type,
|
||||
:note => some_notes,
|
||||
:callback_params => callback_params,
|
||||
:enable_crc32_check => false,
|
||||
:rotate => auto_rotate
|
||||
|
||||
**参数**
|
||||
|
||||
:uptoken
|
||||
: 必须,字符串类型(String),调用 `Qiniu::RS.generate_upload_token` 生成的 [用于上传文件的临时授权凭证](#generate-upload-token)
|
||||
|
||||
:file
|
||||
: 必须,字符串类型(String),本地文件可被读取的有效路径
|
||||
|
||||
:bucket
|
||||
: 必须,字符串类型(String),空间名称。
|
||||
|
||||
:key
|
||||
: 必须,字符串类型(String),若把 Bucket 理解为关系性数据库的某个表,那么 key 类似数据库里边某个表的主键ID,需给每一个文件一个UUID用于进行标示。
|
||||
|
||||
:mime_type
|
||||
: 可选,字符串类型(String),文件的 mime-type 值。如若不传入,SDK 会自行计算得出,若计算失败缺省使用 application/octet-stream 代替之。
|
||||
|
||||
:note
|
||||
: 可选,字符串类型(String),为文件添加备注信息。
|
||||
|
||||
:callback_params
|
||||
: 可选,String 或者 Hash 类型,文件上传成功后,七牛云存储向客户方业务服务器发送的回调参数。
|
||||
|
||||
:enable_crc32_check
|
||||
: 可选,Boolean 类型,是否启用文件上传 crc32 校验,缺省为 false 。
|
||||
|
||||
:rotate
|
||||
: 可选,数字类型,上传图片时专用,可针对图片上传后进行旋转。该参数值为 0 :表示根据图像EXIF信息自动旋转;值为 1 : 右转90度;值为 2 :右转180度;值为 3 : 右转270度。
|
||||
|
||||
**返回值**
|
||||
|
||||
上传成功,返回如下一个 Hash:
|
||||
|
||||
{"hash"=>"FgHk-_iqpnZji6PsNr4ghsK5qEwR"}
|
||||
|
||||
上传失败,会抛出 `UploadFailedError` 异常。
|
||||
|
||||
<a name="resumable-upload"></a>
|
||||
|
||||
##### 开启断点续上传
|
||||
|
||||
无需任何额外改动,SDK 提供的 `Qiniu::RS.upload_file()` 方法缺省支持断点续上传。默认情况下,SDK 会自动启用断点续上传的方式来上传超过 4MB 大小的文件。您也可以在 [应用接入](http://docs.qiniutek.com/v3/sdk/ruby/#establish_connection!) 时通过修改缺省配置来设置该阀值:
|
||||
|
||||
Qiniu::RS.establish_connection! :access_key => YOUR_APP_ACCESS_KEY,
|
||||
:secret_key => YOUR_APP_SECRET_KEY,
|
||||
:block_size => 1024*1024*4,
|
||||
:chunk_size => 1024*256,
|
||||
:tmpdir => Dir.tmpdir + File::SEPARATOR + 'Qiniu-RS-Ruby-SDK',
|
||||
:enable_debug => true,
|
||||
:auto_reconnect => true,
|
||||
:max_retry_times => 3
|
||||
|
||||
**参数详解**
|
||||
|
||||
应用接入初始化时,以下配置参数均为可选:
|
||||
|
||||
:block_size
|
||||
: 整型,指定断点续上传针对大文件所使用的分块大小,缺省为 4MB ,小于该阀值的文件不启用断点续上传。
|
||||
|
||||
:chunk_size
|
||||
: 整型,指定断点续上传每次http请求上传的数据块大小,缺省为 256KB。该设置尽量不要超过实际使用的上行带宽,且不能超过 `:block_size` 定义的值。
|
||||
|
||||
:tmpdir
|
||||
: 字符串类型,指定持久化保存断点续上传进度状态临时文件的目录,缺省放置于操作系统的临时目录中。
|
||||
|
||||
:enable_debug
|
||||
: 布尔值,是否启用调试模式,缺省启用(true),启用后会打印相关日志。该参数 SDK 全局有效。
|
||||
|
||||
:auto_reconnect
|
||||
: 布尔值,指定每次 http 若请求失败是否启用重试,缺省启用(true)。该参数 SDK 全局有效。
|
||||
|
||||
:max_retry_times
|
||||
: 整型,指定每次 http 若请求失败最多可以重试的次数,缺省为3次。该参数 SDK 全局有效。
|
||||
|
||||
|
||||
<a name="upload-client-side"></a>
|
||||
|
||||
#### iOS / Android / Web 端直传文件说明
|
||||
|
||||
客户端 iOS / Android / Web 上传流程和服务端上传类似,差别在于:客户端直传文件所需的 `uploadToken` 选择在客户方的业务服务器端生成,然后将其生成的 `uploadToken` 颁发给客户端。
|
||||
|
||||
简单来讲,客户端上传流程分为两步:
|
||||
|
||||
1. [服务端生成上传授权凭证(uploadToken)](#generate-upload-token)
|
||||
2. 客户端程序调用 [iOS](http://docs.qiniu.com/ios-sdk/index.html) / [Android](http://docs.qiniu.com/android-sdk/index.html) SDK 的文件上传方法进行上传
|
||||
|
||||
如果是网页直传文件到七牛云存储,网页可以使用 JavaScript 动态实现 [七牛云存储上传API](http://docs.qiniutek.com/v3/api/io/#upload-file-by-html-form)。
|
||||
|
||||
通过客户端直传文件,您的终端用户即可把数据(比如图片或视频)直接上传到七牛云存储服务器上,而无须经由您的服务端中转,终端用户上传数据始终是离他物理距离最近的七牛存储节点。当终端用户上传成功后,七牛云存储服务端会向您指定的 `callback_url` (一般在 [uploadToken](#generate-upload-token) 里边指定)发送回调数据(回调数据在客户端程序里边指定)。如果 `callback_url` 所指向的服务端处理完毕后输出 `JSON` 格式的数据,七牛云存储服务端会将该回调请求所得的 JSON 响应信息原封不动地返回给客户端应用程序。
|
||||
|
||||
|
||||
<a name="download"></a>
|
||||
|
||||
### 文件下载
|
||||
|
||||
七牛云存储上的资源下载分为 [公有资源下载](#download-public-files) 和 [私有资源下载](#download-private-files) 。
|
||||
|
||||
私有(private)是 Bucket(空间)的一个属性,一个私有 Bucket 中的资源为私有资源,私有资源不可匿名下载。
|
||||
|
||||
新创建的空间(Bucket)缺省为私有,也可以将某个 Bucket 设为公有,公有 Bucket 中的资源为公有资源,公有资源可以匿名下载。
|
||||
|
||||
<a name="download-public-files"></a>
|
||||
|
||||
#### 公有资源下载
|
||||
|
||||
[GET] http://<bucket>.qiniudn.com/<key>
|
||||
|
||||
或者,
|
||||
|
||||
[GET] http://<绑定域名>/<key>
|
||||
|
||||
绑定域名可以是自定义域名,可以在 [七牛云存储开发者自助网站](https://portal.qiniu.com/) 进行域名绑定操作。
|
||||
|
||||
**注意**,尖括号不是必需,代表替换项。
|
||||
|
||||
<a name="download-private-files"></a>
|
||||
|
||||
#### 私有资源下载
|
||||
|
||||
私有资源只能通过临时下载授权凭证(downloadToken)下载,下载链接格式如下:
|
||||
|
||||
[GET] http://<bucket>.qiniudn.com/<key>?token=<downloadToken>
|
||||
|
||||
或者,
|
||||
|
||||
[GET] http://<绑定域名>/<key>?token=<downloadToken>
|
||||
|
||||
<a name="download-token"></a>
|
||||
|
||||
##### 生成下载授权凭证(downloadToken)
|
||||
|
||||
`<downloadToken>` 可以使用 SDK 提供的如下方法生成:
|
||||
|
||||
Qiniu::RS.generate_download_token :expires_in => expires_in_seconds,
|
||||
:pattern => download_url_patterns
|
||||
|
||||
**参数**
|
||||
|
||||
expires_in
|
||||
: 可选,数字类型,用于设置上传 URL 的有效期,单位:秒,缺省为 3600 秒,即 1 小时后该下载授权凭证(downloadToken)不再有效。
|
||||
|
||||
pattern
|
||||
: 必选,字符串类型,用于设置可匹配的下载链接。参考:[downloadToken pattern 详解](http://docs.qiniutek.com/v3/api/io/#download-token-pattern)
|
||||
|
||||
|
||||
<a name="other-download-features"></a>
|
||||
|
||||
#### 高级特性
|
||||
|
||||
<a name="resumable-download"></a>
|
||||
|
||||
##### 断点续下载
|
||||
|
||||
七牛云存储支持标准的断点续下载,参考:[云存储API之断点续下载](http://docs.qiniu.com/api/get.html#download-by-range-bytes)
|
||||
|
||||
<a name="upload-file-for-not-found"></a>
|
||||
|
||||
##### 自定义 404 NotFound
|
||||
|
||||
您可以上传一个应对 HTTP 404 出错处理的文件,当用户访问一个不存在的文件时,即可使用您上传的“自定义404文件”代替之。要这么做,您只须使用 `Qiniu::RS.upload_file` 函数上传一个 `key` 为固定字符串类型的值 `errno-404` 即可。
|
||||
|
||||
除了使用 SDK 提供的方法,同样也可以借助七牛云存储提供的命令行辅助工具 [qboxrsctl](http://docs.qiniu.com/tools/qboxrsctl.html) 达到同样的目的:
|
||||
|
||||
qboxrsctl put <Bucket> <Key> <LocalFile>
|
||||
|
||||
将其中的 `<Key>` 换作 `errno-404` 即可。
|
||||
|
||||
注意,每个 `<Bucket>` 里边有且只有一个 `errno-404` 文件,上传多个,最后的那一个会覆盖前面所有的。
|
||||
|
||||
|
||||
<a name="file-management"></a>
|
||||
|
||||
### 文件管理
|
||||
|
||||
文件管理包括对存储在七牛云存储上的文件进行查看、复制、移动和删除处理。
|
||||
|
||||
<a name="stat"></a>
|
||||
|
||||
#### 查看单个文件属性信息
|
||||
|
||||
Qiniu::RS.stat(bucket, key)
|
||||
|
||||
可以通过 SDK 提供的 `Qiniu::RS.stat` 函数,来查看某个已上传文件的属性信息。
|
||||
|
||||
**参数**
|
||||
|
||||
bucket
|
||||
: 必须,字符串类型(String),空间名称。
|
||||
|
||||
key
|
||||
: 必须,字符串类型(String),若把 Bucket 理解为关系性数据库的某个表,那么 key 类似数据库里边某个表的主键ID,需给每一个文件一个UUID用于进行标示。
|
||||
|
||||
**返回值**
|
||||
|
||||
如果请求失败,返回 `false`;否则返回如下一个 `Hash` 类型的结构:
|
||||
|
||||
{
|
||||
"fsize" => 3053,
|
||||
"hash" => "Fu9lBSwQKbWNlBLActdx8-toAajv",
|
||||
"mimeType" => "application/x-ruby",
|
||||
"putTime" => 13372775859344500
|
||||
}
|
||||
|
||||
fsize
|
||||
: 表示文件总大小,单位是 Byte
|
||||
|
||||
hash
|
||||
: 文件的特征值,可以看做是基版本号
|
||||
|
||||
mimeType
|
||||
: 文件的 mime-type
|
||||
|
||||
putTime
|
||||
: 上传时间,单位是 百纳秒
|
||||
|
||||
|
||||
<a name="copy"></a>
|
||||
|
||||
#### 复制单个文件
|
||||
|
||||
Qiniu::RS.copy(source_bucket, source_key, target_bucket, target_key)
|
||||
|
||||
可以通过 SDK 提供的 `Qiniu::RS.copy` 函数进行文件复制操作。
|
||||
|
||||
**参数**
|
||||
|
||||
source_bucket
|
||||
: 必须,字符串类型(String),指定源空间。
|
||||
|
||||
source_key
|
||||
: 必须,字符串类型(String),指定源文件。
|
||||
|
||||
target_bucket
|
||||
: 必须,字符串类型(String),指定要复制到的目标空间。
|
||||
|
||||
target_key
|
||||
: 必须,字符串类型(String),指定要复制到目标空间的目标文件名。
|
||||
|
||||
**返回值**
|
||||
|
||||
如果请求失败,返回 `false`;否则返回 `true` 。
|
||||
|
||||
|
||||
<a name="move"></a>
|
||||
|
||||
#### 移动单个文件
|
||||
|
||||
Qiniu::RS.move(source_bucket, source_key, target_bucket, target_key)
|
||||
|
||||
可以通过 SDK 提供的 `Qiniu::RS.move` 函数进行文件移动操作。
|
||||
|
||||
**参数**
|
||||
|
||||
source_bucket
|
||||
: 必须,字符串类型(String),指定源空间。
|
||||
|
||||
source_key
|
||||
: 必须,字符串类型(String),指定源文件。
|
||||
|
||||
target_bucket
|
||||
: 必须,字符串类型(String),指定要移动到的目标空间。
|
||||
|
||||
target_key
|
||||
: 必须,字符串类型(String),指定要移动到目标空间的目标文件名。
|
||||
|
||||
**返回值**
|
||||
|
||||
如果请求失败,返回 `false`;否则返回 `true` 。
|
||||
|
||||
|
||||
<a name="delete"></a>
|
||||
|
||||
### 删除单个文件
|
||||
|
||||
Qiniu::RS.delete(bucket, key)
|
||||
|
||||
`Qiniu::RS.delete` 函数提供了从指定的 `bucket` 中删除指定的 `key`,即删除 `key` 索引关联的具体文件。
|
||||
|
||||
**参数**
|
||||
|
||||
bucket
|
||||
: 必须,字符串类型(String),空间名称。
|
||||
|
||||
key
|
||||
: 必须,字符串类型(String),若把 Bucket 理解为关系性数据库的某个表,那么 key 类似数据库里边某个表的主键ID,需给每一个文件一个UUID用于进行标示。
|
||||
|
||||
**返回值**
|
||||
|
||||
如果删除成功,返回 `true`,否则返回 `false` 。
|
||||
|
||||
|
||||
<a name="batch"></a>
|
||||
|
||||
### 批量操作
|
||||
|
||||
Qiniu::RS.batch(command, bucket, keys)
|
||||
|
||||
SDK 还提供了 `Qiniu::RS.batch` 函数来提供批量处理 `Qiniu::RS.stat` 或是 `Qiniu::RS.get` 或 `Qiniu::RS.delete` 的相应功能。
|
||||
|
||||
**参数**
|
||||
|
||||
command
|
||||
: 必须,字符串类型(String),其值可以是 `stat`, `get`, `delete` 中的一种
|
||||
|
||||
bucket
|
||||
: 必须,字符串类型(String),空间名称。
|
||||
|
||||
keys
|
||||
: 必须,数组类型(Array),所要操作 `key` 的集合。
|
||||
|
||||
**返回值**
|
||||
|
||||
如果请求失败,返回 `false`,否则返回一个 `Array` 类型的结构,其中每个元素是一个 `Hash` 类型的结构。例如批量`get`:
|
||||
|
||||
[
|
||||
{
|
||||
"code" => 200,
|
||||
"data" => {
|
||||
"expires" => 3600,
|
||||
"fsize" => 3053,
|
||||
"hash" => "Fu9lBSwQKbWNlBLActdx8-toAajv",
|
||||
"mimeType" => "application/x-ruby",
|
||||
"url" => "http://iovip.qbox.me/file/<an-authorized-token>"
|
||||
}
|
||||
},
|
||||
...
|
||||
]
|
||||
|
||||
<a name="batch-get"></a>
|
||||
|
||||
#### 批量获取文件属性信息
|
||||
|
||||
Qiniu::RS.batch_get(bucket, keys)
|
||||
|
||||
`Qiniu::RS.batch_get` 函数是在 `Qiniu::RS.batch` 之上的封装,提供批量获取文件属性信息(含下载链接)的功能。
|
||||
|
||||
**参数**
|
||||
|
||||
bucket
|
||||
: 必须,字符串类型(String),空间名称。
|
||||
|
||||
keys
|
||||
: 必须,数组类型(Array),所要操作 `key` 的集合。
|
||||
|
||||
**返回值**
|
||||
|
||||
如果请求失败,返回 `false`,否则返回一个 `Array` 类型的结构,其中每个元素是一个 `Hash` 类型的结构。`Hash` 类型的值同 `Qiniu::RS.get` 函数的返回值类似,只多出一个 `code` 字段,`code` 为 200 表示所有 keys 全部获取成功,`code` 若为 298 表示部分获取成功。
|
||||
|
||||
[
|
||||
{
|
||||
"code" => 200,
|
||||
"data" => {
|
||||
"expires" => 3600,
|
||||
"fsize" => 3053,
|
||||
"hash" => "Fu9lBSwQKbWNlBLActdx8-toAajv",
|
||||
"mimeType" => "application/x-ruby",
|
||||
"url" => "http://iovip.qbox.me/file/<an-authorized-token>"
|
||||
}
|
||||
},
|
||||
...
|
||||
]
|
||||
|
||||
|
||||
<a name="batch-copy"></a>
|
||||
|
||||
#### 批量复制文件
|
||||
|
||||
Qiniu::RS.batch_copy(*args)
|
||||
|
||||
等价于,
|
||||
|
||||
Qiniu::RS.batch_copy [source_bucket, source_key, target_bucket, target_key], ...
|
||||
|
||||
`Qiniu::RS.batch_copy()` 的参数是一个可变长数组,其中每个数组其元素含义同 `Qiniu::RS.copy` 的参数一样。
|
||||
|
||||
**返回值**
|
||||
|
||||
如果批量删除成功,返回 `true` ,否则为 `false` 。
|
||||
|
||||
|
||||
<a name="batch-move"></a>
|
||||
|
||||
#### 批量移动文件
|
||||
|
||||
Qiniu::RS.batch_move(*args)
|
||||
|
||||
等价于,
|
||||
|
||||
Qiniu::RS.batch_move [source_bucket, source_key, target_bucket, target_key], ...
|
||||
|
||||
`Qiniu::RS.batch_move()` 的参数是一个可变长数组,其中每个数组其元素含义同 `Qiniu::RS.move` 的参数一样。
|
||||
|
||||
**返回值**
|
||||
|
||||
如果批量删除成功,返回 `true` ,否则为 `false` 。
|
||||
|
||||
|
||||
<a name="batch-delete"></a>
|
||||
|
||||
#### 批量删除文件
|
||||
|
||||
Qiniu::RS.batch_delete(bucket, keys)
|
||||
|
||||
`Qiniu::RS.batch_download` 函数也是在 `Qiniu::RS.batch` 之上的封装,提供批量删除文件的功能。
|
||||
|
||||
参数同 `Qiniu::RS.batch_get` 的参数一样。
|
||||
|
||||
**返回值**
|
||||
|
||||
如果批量删除成功,返回 `true` ,否则为 `false` 。
|
||||
|
||||
|
||||
<a name="cloud-processing"></a>
|
||||
|
||||
### 云处理
|
||||
|
||||
<a name="image-processing"></a>
|
||||
|
||||
#### 图像
|
||||
|
||||
<a name="image-info"></a>
|
||||
|
||||
##### 查看图片属性信息
|
||||
|
||||
Qiniu::RS.image_info(url)
|
||||
|
||||
使用 SDK 提供的 `Qiniu::RS.image_info` 方法,可以基于一张存储于七牛云存储服务器上的图片,针对其下载链接来获取该张图片的属性信息。
|
||||
|
||||
**参数**
|
||||
|
||||
url
|
||||
: 必须,字符串类型(String),图片的下载链接,需是 `Qiniu::RS.get`(或`Qiniu::RS.batch_get`)函数返回值中 `url` 字段的值,或者是 `Qiniu::RS.download`(或`Qiniu::RS.batch_download`)函数返回的下载链接。且文件本身必须是图片。
|
||||
|
||||
**返回值**
|
||||
|
||||
如果请求失败,返回 `false`;否则,返回如下一个 `Hash` 类型的结构:
|
||||
|
||||
{
|
||||
"format" => "jpeg",
|
||||
"width" => 640,
|
||||
"height" => 425,
|
||||
"colorModel" => "ycbcr"
|
||||
}
|
||||
|
||||
format
|
||||
: 原始图片类型
|
||||
|
||||
width
|
||||
: 原始图片宽度,单位像素
|
||||
|
||||
height
|
||||
: 原始图片高度,单位像素
|
||||
|
||||
colorModel
|
||||
: 原始图片着色模式
|
||||
|
||||
<a name="image-exif"></a>
|
||||
|
||||
##### 查看图片EXIF信息
|
||||
|
||||
Qiniu::RS.image_exif(url)
|
||||
|
||||
使用 SDK 提供的 `Qiniu::RS.image_exif` 方法,可以基于一张存储于七牛云存储服务器上的原始图片图片,取到该图片的 EXIF 信息。
|
||||
|
||||
**参数**
|
||||
|
||||
url
|
||||
: 必须,字符串类型(String),原图的下载链接,需是 `Qiniu::RS.get`(或`Qiniu::RS.batch_get`)函数返回值中 `url` 字段的值,或者是 `Qiniu::RS.download`(或`Qiniu::RS.batch_download`)函数返回的下载链接。且文件本身必须是图片。
|
||||
|
||||
**返回值**
|
||||
|
||||
如果参数 `url` 所代表的图片没有 EXIF 信息,返回 `false`。否则,返回一个包含 EXIF 信息的 Hash 结构。
|
||||
|
||||
<a name="image-mogrify-for-preview"></a>
|
||||
|
||||
##### 图像在线处理(缩略、裁剪、旋转、转化)
|
||||
|
||||
`Qiniu::RS.image_mogrify_preview_url()` 方法支持将一个存储在七牛云存储的图片进行缩略、裁剪、旋转和格式转化处理,该方法返回一个可以直接预览缩略图的URL。
|
||||
|
||||
image_mogrify_preview_url = Qiniu::RS.image_mogrify_preview_url(source_image_url, mogrify_options)
|
||||
|
||||
**参数**
|
||||
|
||||
source_image_url
|
||||
: 必须,字符串类型(string),指定原始图片的下载链接,可以根据 rs.get() 获取到。
|
||||
|
||||
mogrify_options
|
||||
: 必须,Hash Map 格式的图像处理参数。
|
||||
|
||||
`mogrify_options` 对象具体的规格如下:
|
||||
|
||||
mogrify_options = {
|
||||
:thumbnail => <ImageSizeGeometry>,
|
||||
:gravity => <GravityType>, =NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast
|
||||
:crop => <ImageSizeAndOffsetGeometry>,
|
||||
:quality => <ImageQuality>,
|
||||
:rotate => <RotateDegree>,
|
||||
:format => <DestinationImageFormat>, =jpg, gif, png, tif, etc.
|
||||
:auto_orient => <TrueOrFalse>
|
||||
}
|
||||
|
||||
`Qiniu::RS.image_mogrify_preview_url()` 方法是对七牛云存储图像处理高级接口的完整包装,关于 `mogrify_options` 参数里边的具体含义和使用方式,可以参考文档:[图像处理高级接口](http://docs.qiniu.com/api/image-process.html#imageMogr)。
|
||||
|
||||
**返回值**
|
||||
|
||||
返回一个可以预览最终缩略图的URL,String 类型。
|
||||
|
||||
<a name="image-mogrify-for-save-as"></a>
|
||||
|
||||
#### 图像在线处理(缩略、裁剪、旋转、转化)后并持久化存储
|
||||
|
||||
`Qiniu::RS.image_mogrify_save_as()` 方法支持将一个存储在七牛云存储的图片进行缩略、裁剪、旋转和格式转化处理,并且将处理后的缩略图作为一个新文件持久化存储到七牛云存储服务器上,这样就可以供后续直接使用而不用每次都传入参数进行图像处理。
|
||||
|
||||
result = Qiniu::RS.image_mogrify_save_as(target_bucket, target_key, src_img_url, mogrify_options)
|
||||
|
||||
**参数**
|
||||
|
||||
target_bucket
|
||||
: 必须,字符串类型(string),指定最终缩略图要存放的 bucket 。
|
||||
|
||||
target_key
|
||||
: 必须,字符串类型(string),指定最终缩略图存放在云存储服务端的唯一文件ID。
|
||||
|
||||
src_img_url
|
||||
: 必须,字符串类型(string),指定原始图片的下载链接,可以根据 rs.get() 获取到。
|
||||
|
||||
mogrify_options
|
||||
: 必须,Hash Map 格式的图像处理参数。
|
||||
|
||||
`mogrify_options` 对象具体的规格如下:
|
||||
|
||||
mogrify_options = {
|
||||
:thumbnail => <ImageSizeGeometry>,
|
||||
:gravity => <GravityType>, =NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast
|
||||
:crop => <ImageSizeAndOffsetGeometry>,
|
||||
:quality => <ImageQuality>,
|
||||
:rotate => <RotateDegree>,
|
||||
:format => <DestinationImageFormat>, =jpg, gif, png, tif, etc.
|
||||
:auto_orient => <TrueOrFalse>
|
||||
}
|
||||
|
||||
`Qiniu::RS::Image.mogrify_preview_url()` 方法是对七牛云存储图像处理高级接口的完整包装,关于 `mogrify_options` 参数里边的具体含义和使用方式,可以参考文档:[图像处理高级接口](http://docs.qiniu.com/api/image-process.html#imageMogr)
|
||||
|
||||
**返回值**
|
||||
|
||||
如果请求失败,返回 `false`;否则,返回如下一个 `Hash` 类型的结构:
|
||||
|
||||
{"hash" => "FrOXNat8VhBVmcMF3uGrILpTu8Cs"}
|
||||
|
||||
示例代码:
|
||||
|
||||
data = Qiniu::RS.get("<test_image_bucket>", "<test_image_key>")
|
||||
src_img_url = data["url"]
|
||||
|
||||
target_bucket = "test_thumbnails_bucket"
|
||||
target_key = "cropped-" + @test_image_key
|
||||
|
||||
mogrify_options = {
|
||||
:thumbnail => "!120x120r",
|
||||
:gravity => "center",
|
||||
:crop => "!120x120a0a0",
|
||||
:quality => 85,
|
||||
:rotate => 45,
|
||||
:format => "jpg",
|
||||
:auto_orient => true
|
||||
}
|
||||
|
||||
result = Qiniu::RS.image_mogrify_save_as(target_bucket, target_key, src_img_url, mogrify_options)
|
||||
if result
|
||||
thumbnail = Qiniu::RS.get(target_bucket, target_key)
|
||||
puts thumbnail["url"]
|
||||
|
||||
# 您可以选择将存放缩略图的 bucket 公开,这样就可以直接以外链的形式访问到缩略图,而不用走API获取下载URL,就可以直接以如下方式访问缩略图:
|
||||
|
||||
# [GET] http://<bucket>.qiniudn.com/<target_key>
|
||||
end
|
||||
|
||||
|
||||
<a name="Contributing"></a>
|
||||
|
||||
## 贡献代码
|
||||
|
||||
七牛云存储 Ruby SDK 源码地址:<https://github.com/qiniu/ruby-sdk>
|
||||
|
||||
1. 登录 <https://github.com>
|
||||
2. Fork <https://github.com/qiniu/ruby-sdk>
|
||||
3. 创建您的特性分支 (`git checkout -b my-new-feature`)
|
||||
4. 提交您的改动 (`git commit -am 'Added some feature'`)
|
||||
5. 将您的改动记录提交到远程 `git` 仓库 (`git push origin my-new-feature`)
|
||||
6. 然后到 github 网站的该 `git` 远程仓库的 `my-new-feature` 分支下发起 Pull Request
|
||||
|
||||
<a name="License"></a>
|
||||
|
||||
## 许可证
|
||||
|
||||
Copyright (c) 2012 qiniutek.com
|
||||
|
||||
基于 MIT 协议发布:
|
||||
|
||||
* [www.opensource.org/licenses/MIT](http://www.opensource.org/licenses/MIT)
|
||||
+1
-1
@@ -1,2 +1,2 @@
|
||||
# More logical way to require 'qiniu-rs'
|
||||
require File.join(File.dirname(__FILE__), 'qiniu', 'rs')
|
||||
require File.join(File.dirname(__FILE__), 'qiniu', 'qiniu')
|
||||
|
||||
Executable
+213
@@ -0,0 +1,213 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
module Qiniu
|
||||
autoload :Version, 'qiniu/version'
|
||||
autoload :Utils, 'qiniu/utils'
|
||||
autoload :Auth, 'qiniu/auth'
|
||||
autoload :Config, 'qiniu/config'
|
||||
autoload :Log, 'qiniu/log'
|
||||
autoload :Exception, 'qiniu/exceptions'
|
||||
autoload :AccessToken, 'qiniu/tokens/access_token'
|
||||
autoload :QboxToken, 'qiniu/tokens/qbox_token'
|
||||
autoload :UploadToken, 'qiniu/tokens/upload_token'
|
||||
autoload :DownloadToken, 'qiniu/tokens/download_token'
|
||||
autoload :Abstract, 'qiniu/abstract'
|
||||
autoload :Storage, 'qiniu/storage'
|
||||
autoload :Fop, 'qiniu/fop'
|
||||
autoload :Misc, 'qiniu/misc'
|
||||
|
||||
class << self
|
||||
|
||||
StatusOK = 200
|
||||
|
||||
def establish_connection!(opts = {})
|
||||
Config.initialize_connect opts
|
||||
end
|
||||
|
||||
def mkbucket(bucket_name)
|
||||
code, data = Storage.mkbucket(bucket_name)
|
||||
code == StatusOK
|
||||
end
|
||||
|
||||
def buckets
|
||||
code, data = Storage.buckets
|
||||
code == StatusOK ? data : false
|
||||
end
|
||||
|
||||
def set_protected(bucket, protected_mode)
|
||||
code, data = Misc.set_protected(bucket, protected_mode)
|
||||
code == StatusOK
|
||||
end
|
||||
|
||||
def set_separator(bucket, separator)
|
||||
code, data = Misc.set_separator(bucket, separator)
|
||||
code == StatusOK
|
||||
end
|
||||
|
||||
def set_style(bucket, name, style)
|
||||
code, data = Misc.set_style(bucket, name, style)
|
||||
code == StatusOK
|
||||
end
|
||||
|
||||
def unset_style(bucket, name)
|
||||
code, data = Misc.unset_style(bucket, name)
|
||||
code == StatusOK
|
||||
end
|
||||
|
||||
def upload_file opts = {}
|
||||
uncontained_opts = [:uptoken, :file, :bucket, :key] - opts.keys
|
||||
raise MissingArgsError, uncontained_opts unless uncontained_opts.empty?
|
||||
|
||||
source_file = opts[:file]
|
||||
raise NoSuchFileError, source_file unless File.exist?(source_file)
|
||||
|
||||
opts[:enable_resumable_upload] = true unless opts.has_key?(:enable_resumable_upload)
|
||||
|
||||
if opts[:enable_resumable_upload] && File::size(source_file) > Config.settings[:block_size]
|
||||
code, data, raw_headers = Storage.resumable_upload_with_token(opts[:uptoken],
|
||||
opts[:file],
|
||||
opts[:bucket],
|
||||
opts[:key],
|
||||
opts[:mime_type],
|
||||
opts[:customer],
|
||||
opts[:callback_params],
|
||||
opts[:rotate])
|
||||
else
|
||||
code, data, raw_headers = Storage.upload_with_token(opts[:uptoken],
|
||||
opts[:file],
|
||||
opts[:bucket],
|
||||
opts[:key],
|
||||
opts[:mime_type],
|
||||
opts[:note],
|
||||
opts[:callback_params],
|
||||
opts[:enable_crc32_check],
|
||||
opts[:rotate])
|
||||
end
|
||||
raise UploadFailedError.new(code, data) if code != StatusOK
|
||||
return data
|
||||
end
|
||||
|
||||
def stat(bucket, key)
|
||||
code, data = Storage.stat(bucket, key)
|
||||
code == StatusOK ? data : false
|
||||
end
|
||||
|
||||
def get(bucket, key, save_as = nil, expires_in = nil, version = nil)
|
||||
code, data = Storage.get(bucket, key, save_as, expires_in, version)
|
||||
code == StatusOK ? data : false
|
||||
end
|
||||
|
||||
def download(bucket, key, save_as = nil, expires_in = nil, version = nil)
|
||||
code, data = Storage.get(bucket, key, save_as, expires_in, version)
|
||||
code == StatusOK ? data["url"] : false
|
||||
end
|
||||
|
||||
def copy(source_bucket, source_key, target_bucket, target_key)
|
||||
code, data = Storage.copy(source_bucket, source_key, target_bucket, target_key)
|
||||
code == StatusOK
|
||||
end
|
||||
|
||||
def move(source_bucket, source_key, target_bucket, target_key)
|
||||
code, data = Storage.move(source_bucket, source_key, target_bucket, target_key)
|
||||
code == StatusOK
|
||||
end
|
||||
|
||||
def delete(bucket, key)
|
||||
code, data = Storage.delete(bucket, key)
|
||||
code == StatusOK
|
||||
end
|
||||
|
||||
def fetch(bucket, target_url, key)
|
||||
code, data = Storage.fetch(bucket, target_url, key)
|
||||
code == StatusOK
|
||||
end
|
||||
|
||||
def batch(command, bucket, keys)
|
||||
code, data = Storage.batch(command, bucket, keys)
|
||||
code == StatusOK ? data : false
|
||||
end
|
||||
|
||||
def batch_stat(bucket, keys)
|
||||
code, data = Storage.batch_stat(bucket, keys)
|
||||
code == StatusOK ? data : false
|
||||
end
|
||||
|
||||
def batch_get(bucket, keys)
|
||||
code, data = Storage.batch_get(bucket, keys)
|
||||
code == StatusOK ? data : false
|
||||
end
|
||||
|
||||
def batch_copy(*args)
|
||||
code, data = Storage.batch_copy(args)
|
||||
code == StatusOK
|
||||
end
|
||||
|
||||
def batch_move(*args)
|
||||
code, data = Storage.batch_move(args)
|
||||
code == StatusOK
|
||||
end
|
||||
|
||||
def batch_download(bucket, keys)
|
||||
code, data = Storage.batch_get(bucket, keys)
|
||||
return false unless code == StatusOK
|
||||
links = []
|
||||
data.each { |e| links << e["data"]["url"] }
|
||||
links
|
||||
end
|
||||
|
||||
def batch_delete(bucket, keys)
|
||||
code, data = Storage.batch_delete(bucket, keys)
|
||||
code == StatusOK ? data : false
|
||||
end
|
||||
|
||||
def drop(bucket)
|
||||
code, data = Storage.drop(bucket)
|
||||
code == StatusOK
|
||||
end
|
||||
|
||||
def image_info(url)
|
||||
code, data = Fop::Image.info(url)
|
||||
code == StatusOK ? data : false
|
||||
end
|
||||
|
||||
def image_exif(url)
|
||||
code, data = Fop::Image.exif(url)
|
||||
code == StatusOK ? data : false
|
||||
end
|
||||
|
||||
def image_mogrify_preview_url(source_image_url, options)
|
||||
Fop::Image.mogrify_preview_url(source_image_url, options)
|
||||
end
|
||||
|
||||
def image_mogrify_save_as(bucket, key, source_image_url, options)
|
||||
code, data = Storage.image_mogrify_save_as(bucket, key, source_image_url, options)
|
||||
code == StatusOK ? data : false
|
||||
end
|
||||
|
||||
def generate_upload_token(opts = {})
|
||||
token_obj = UploadToken.new(opts)
|
||||
token_obj.access_key = Config.settings[:access_key]
|
||||
token_obj.secret_key = Config.settings[:secret_key]
|
||||
#token_obj.scope = opts[:scope]
|
||||
#token_obj.expires_in = opts[:expires_in]
|
||||
#token_obj.callback_url = opts[:callback_url]
|
||||
#token_obj.callback_body_type = opts[:callback_body_type]
|
||||
#token_obj.customer = opts[:customer]
|
||||
#token_obj.escape = opts[:escape]
|
||||
#token_obj.async_options = opts[:async_options]
|
||||
#token_obj.return_body = opts[:return_body]
|
||||
token_obj.generate_token
|
||||
end
|
||||
|
||||
def generate_download_token(opts = {})
|
||||
token_obj = DownloadToken.new(opts)
|
||||
token_obj.access_key = Config.settings[:access_key]
|
||||
token_obj.secret_key = Config.settings[:secret_key]
|
||||
#token_obj.expires_in = opts[:expires_in]
|
||||
#token_obj.pattern = opts[:pattern]
|
||||
token_obj.generate_token
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
end # module Qiniu
|
||||
@@ -0,0 +1,22 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
module Qiniu
|
||||
module Abstract
|
||||
def self.included(base)
|
||||
base.extend(ClassMethods)
|
||||
end
|
||||
|
||||
module ClassMethods
|
||||
def abstract_methods(*args)
|
||||
args.each do |name|
|
||||
class_eval <<-END
|
||||
def #{name}(*args)
|
||||
errmsg = %Q(class \#{self.class.name} must implement abstract method #{self.name}##{name}().)
|
||||
raise NotImplementedError.new(errmsg)
|
||||
end
|
||||
END
|
||||
end
|
||||
end
|
||||
end
|
||||
end # module Abstract
|
||||
end # module Qiniu
|
||||
@@ -0,0 +1,46 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
# vim: sw=2 ts=2
|
||||
|
||||
require 'uri'
|
||||
|
||||
module Qiniu
|
||||
module ADT
|
||||
|
||||
class ApiSpecification
|
||||
public
|
||||
def to_str; return ""; end
|
||||
end # class ApiSpecification
|
||||
|
||||
module Policy
|
||||
public
|
||||
def to_json
|
||||
args = {}
|
||||
|
||||
self.params.each_pair do |key, fld|
|
||||
val = self.__send__(key)
|
||||
if !val.nil? then
|
||||
args[fld] = val
|
||||
end
|
||||
end
|
||||
|
||||
return args.to_json
|
||||
end # to_json
|
||||
|
||||
def to_query_string
|
||||
args = []
|
||||
|
||||
self.params.each_pair do |key, fld|
|
||||
val = self.__send__(key)
|
||||
if !val.nil? then
|
||||
new_fld = CGI.escape(fld.to_s)
|
||||
new_val = CGI.escape(val.to_s).gsub('+', '%20')
|
||||
args.push("#{new_fld}=#{new_val}")
|
||||
end
|
||||
end
|
||||
|
||||
return args.join("&")
|
||||
end # to_query_string
|
||||
end # module Policy
|
||||
|
||||
end # module ADT
|
||||
end # module Qiniu
|
||||
Executable
+285
@@ -0,0 +1,285 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
# vim: sw=2 ts=2
|
||||
|
||||
require 'hmac-sha1'
|
||||
require 'uri'
|
||||
require 'cgi'
|
||||
|
||||
require 'qiniu/exceptions'
|
||||
|
||||
module Qiniu
|
||||
module Auth
|
||||
DEFAULT_AUTH_SECONDS = 3600
|
||||
|
||||
class << self
|
||||
def calculate_deadline(expires_in, deadline = nil)
|
||||
### 授权期计算
|
||||
if expires_in.is_a?(Integer) && expires_in > 0 then
|
||||
# 指定相对时间,单位:秒
|
||||
return Time.now.to_i + expires_in
|
||||
elsif deadline.is_a?(Integer) then
|
||||
# 指定绝对时间,常用于调试和单元测试
|
||||
return deadline
|
||||
end
|
||||
|
||||
# 默认授权期1小时
|
||||
return Time.now.to_i + DEFAULT_AUTH_SECONDS
|
||||
end # calculate_deadline
|
||||
|
||||
def calculate_hmac_sha1_digest(sk, str)
|
||||
begin
|
||||
sign = HMAC::SHA1.new(sk).update(str).digest
|
||||
rescue RuntimeError => e
|
||||
raise RuntimeError, "Please set Qiniu's access_key and secret_key before authorize any tokens."
|
||||
rescue
|
||||
raise
|
||||
else
|
||||
return sign
|
||||
end
|
||||
end
|
||||
end # class << self
|
||||
|
||||
class PutPolicy
|
||||
private
|
||||
def initialize(bucket,
|
||||
key = nil,
|
||||
expires_in = DEFAULT_AUTH_SECONDS,
|
||||
deadline = nil)
|
||||
### 设定scope参数(必填项目)
|
||||
self.scope!(bucket, key)
|
||||
|
||||
### 设定deadline参数(必填项目)
|
||||
@expires_in = expires_in
|
||||
@deadline = Auth.calculate_deadline(expires_in, deadline)
|
||||
end # initialize
|
||||
|
||||
PARAMS = {
|
||||
# 字符串类型参数
|
||||
:scope => "scope" ,
|
||||
:save_key => "saveKey" ,
|
||||
:end_user => "endUser" ,
|
||||
:return_url => "returnUrl" ,
|
||||
:return_body => "returnBody" ,
|
||||
:callback_url => "callbackUrl" ,
|
||||
:callback_host => "callbackHost" ,
|
||||
:callback_body => "callbackBody" ,
|
||||
:callback_body_type => "callbackBodyType" ,
|
||||
:persistent_ops => "persistentOps" ,
|
||||
:persistent_notify_url => "persistentNotifyUrl" ,
|
||||
:persistent_pipeline => "persistentPipeline" ,
|
||||
|
||||
# 数值类型参数
|
||||
:deadline => "deadline" ,
|
||||
:insert_only => "insertOnly" ,
|
||||
:fsize_limit => "fsizeLimit" ,
|
||||
:callback_fetch_key => "callbackFetchKey" ,
|
||||
:detect_mime => "detectMime" ,
|
||||
:mime_limit => "mimeLimit"
|
||||
} # PARAMS
|
||||
|
||||
public
|
||||
attr_reader :bucket, :key
|
||||
|
||||
def scope!(bucket, key = nil)
|
||||
@bucket = bucket
|
||||
@key = key
|
||||
|
||||
if key.nil? then
|
||||
# 新增语义,文件已存在则失败
|
||||
@scope = bucket
|
||||
else
|
||||
# 覆盖语义,文件已存在则直接覆盖
|
||||
@scope = "#{bucket}:#{key}"
|
||||
end
|
||||
end # scope!
|
||||
|
||||
def expires_in!(seconds)
|
||||
if !seconds.nil? then
|
||||
return @expires_in
|
||||
end
|
||||
|
||||
@epires_in = seconds
|
||||
@deadline = Auth.calculate_deadline(seconds)
|
||||
|
||||
return @expires_in
|
||||
end # expires_in!
|
||||
|
||||
def expires_in=(seconds)
|
||||
return expires_in!(seconds)
|
||||
end # expires_in=
|
||||
|
||||
def expires_in
|
||||
return @expires_in
|
||||
end # expires_in
|
||||
|
||||
def allow_mime_list! (list)
|
||||
@mime_limit = list
|
||||
end # allow_mime_list!
|
||||
|
||||
def deny_mime_list! (list)
|
||||
@mime_limit = "!#{list}"
|
||||
end # deny_mime_list!
|
||||
|
||||
def insert_only!
|
||||
@insert_only = 1
|
||||
end # insert_only!
|
||||
|
||||
def detect_mime!
|
||||
@detect_mime = 1
|
||||
end # detect_mime!
|
||||
|
||||
def to_json
|
||||
args = {}
|
||||
|
||||
PARAMS.each_pair do |key, fld|
|
||||
val = self.__send__(key)
|
||||
if !val.nil? then
|
||||
args[fld] = val
|
||||
end
|
||||
end
|
||||
|
||||
return args.to_json
|
||||
end # to_json
|
||||
|
||||
PARAMS.each_pair do |key, fld|
|
||||
attr_accessor key
|
||||
end
|
||||
end # class PutPolicy
|
||||
|
||||
class << self
|
||||
EMPTY_ARGS = {}
|
||||
|
||||
### 生成下载授权URL
|
||||
def authorize_download_url(url, args = EMPTY_ARGS)
|
||||
### 提取AK/SK信息
|
||||
access_key = Config.settings[:access_key]
|
||||
secret_key = Config.settings[:secret_key]
|
||||
|
||||
download_url = url
|
||||
|
||||
### URL变换:追加FOP指令
|
||||
if args[:fop].is_a?(String) && args[:fop] != '' then
|
||||
if download_url.index('?').is_a?(Fixnum) then
|
||||
# 已有参数
|
||||
download_url = "#{download_url}&#{args[:fop]}"
|
||||
else
|
||||
# 尚无参数
|
||||
download_url = "#{download_url}?#{args[:fop]}"
|
||||
end
|
||||
end
|
||||
|
||||
### 授权期计算
|
||||
e = Auth.calculate_deadline(args[:expires_in], args[:deadline])
|
||||
|
||||
### URL变换:追加授权期参数
|
||||
if download_url.index('?').is_a?(Fixnum) then
|
||||
# 已有参数
|
||||
download_url = "#{download_url}&e=#{e}"
|
||||
else
|
||||
# 尚无参数
|
||||
download_url = "#{download_url}?e=#{e}"
|
||||
end
|
||||
|
||||
### 生成数字签名
|
||||
sign = calculate_hmac_sha1_digest(secret_key, download_url)
|
||||
encoded_sign = Utils.urlsafe_base64_encode(sign)
|
||||
|
||||
### 生成下载授权凭证
|
||||
dntoken = "#{access_key}:#{encoded_sign}"
|
||||
|
||||
### 返回下载授权URL
|
||||
return "#{download_url}&token=#{dntoken}"
|
||||
end # authorize_download_url
|
||||
|
||||
### 对包含中文或其它 utf-8 字符的 Key 做下载授权
|
||||
def authorize_download_url_2(domain, key, args = EMPTY_ARGS)
|
||||
url_encoded_key = CGI::escape(key)
|
||||
|
||||
schema = args[:schema] || "http"
|
||||
port = args[:port]
|
||||
|
||||
if port.nil? then
|
||||
download_url = "#{schema}://#{domain}/#{url_encoded_key}"
|
||||
else
|
||||
download_url = "#{schema}://#{domain}:#{port}/#{url_encoded_key}"
|
||||
end
|
||||
return authorize_download_url(download_url, args)
|
||||
end # authorize_download_url_2
|
||||
|
||||
def generate_acctoken_sign_with_mac(access_key, secret_key, url, body)
|
||||
### 解析URL,生成待签名字符串
|
||||
uri = URI.parse(url)
|
||||
signing_str = uri.path
|
||||
|
||||
# 如有QueryString部分,则需要加上
|
||||
query_string = uri.query
|
||||
if query_string.is_a?(String) && !query_string.empty?
|
||||
signing_str += '?' + query_string
|
||||
end
|
||||
|
||||
# 追加换行符
|
||||
signing_str += "\n"
|
||||
|
||||
# 如果有Body,则也加上
|
||||
# (仅限于mime == "application/x-www-form-urlencoded"的情况)
|
||||
if body.is_a?(String) && !body.empty?
|
||||
signing_str += body
|
||||
end
|
||||
|
||||
### 生成数字签名
|
||||
sign = calculate_hmac_sha1_digest(secret_key, signing_str)
|
||||
return Utils.urlsafe_base64_encode(sign)
|
||||
end # generate_acctoken_sign_with_mac
|
||||
|
||||
def generate_acctoken(url, body = '')
|
||||
encoded_sign = generate_acctoken_sign_with_mac(Config.settings[:access_key], Config.settings[:secret_key], url, body)
|
||||
return "#{Config.settings[:access_key]}:#{encoded_sign}"
|
||||
end # generate_acctoken
|
||||
|
||||
def generate_uptoken(put_policy)
|
||||
### 提取AK/SK信息
|
||||
access_key = Config.settings[:access_key]
|
||||
secret_key = Config.settings[:secret_key]
|
||||
|
||||
### 生成待签名字符串
|
||||
encoded_put_policy = Utils.urlsafe_base64_encode(put_policy.to_json)
|
||||
|
||||
### 生成数字签名
|
||||
sign = calculate_hmac_sha1_digest(secret_key, encoded_put_policy)
|
||||
encoded_sign = Utils.urlsafe_base64_encode(sign)
|
||||
|
||||
### 生成上传授权凭证
|
||||
uptoken = "#{access_key}:#{encoded_sign}:#{encoded_put_policy}"
|
||||
|
||||
### 返回上传授权凭证
|
||||
return uptoken
|
||||
end # generate_uptoken
|
||||
|
||||
def authenticate_callback_request(auth_str, url, body = '')
|
||||
### 提取AK/SK信息
|
||||
access_key = Config.settings[:access_key]
|
||||
secret_key = Config.settings[:secret_key]
|
||||
|
||||
### 检查签名格式
|
||||
ak_pos = auth_str.index(access_key)
|
||||
if ak_pos.nil? then
|
||||
return false
|
||||
end
|
||||
|
||||
colon_pos = auth_str.index(':', ak_pos + 1)
|
||||
if colon_pos.nil? || ((ak_pos + access_key.length) != colon_pos) then
|
||||
return false
|
||||
end
|
||||
|
||||
encoded_sign = generate_acctoken_sign_with_mac(access_key, secret_key, url, body)
|
||||
sign_pos = auth_str.index(encoded_sign, colon_pos + 1)
|
||||
if sign_pos.nil? || ((sign_pos + encoded_sign.length) != auth_str.length) then
|
||||
return false
|
||||
end
|
||||
|
||||
return true
|
||||
end # authenticate_callback_request
|
||||
end # class << self
|
||||
|
||||
end # module Auth
|
||||
end # module Qiniu
|
||||
@@ -8,37 +8,41 @@
|
||||
# Qbox::Config.load "path/to/your_project/config/qiniu.yml"
|
||||
#
|
||||
|
||||
require "qiniu/rs/version"
|
||||
require 'tmpdir'
|
||||
|
||||
module Qiniu
|
||||
module RS
|
||||
module Config
|
||||
class << self
|
||||
|
||||
DEFAULT_OPTIONS = {
|
||||
:user_agent => 'Qiniu-RS-Ruby-SDK-' + VERSION + '()',
|
||||
:user_agent => 'QiniuRuby/' + Version.to_s + ' ('+RUBY_PLATFORM+')' + ' Ruby/'+ RUBY_VERSION,
|
||||
:method => :post,
|
||||
:content_type => 'application/x-www-form-urlencoded',
|
||||
:auth_url => "https://acc.qbox.me/oauth2/token",
|
||||
:rs_host => "http://rs.qbox.me:10100",
|
||||
#:rs_host => "http://localhost:10100",
|
||||
:io_host => "http://iovip.qbox.me",
|
||||
#:io_host => "http://localhost:10200",
|
||||
:client_id => "a75604760c4da4caaa456c0c5895c061c3065c5a",
|
||||
:client_secret => "75df554a39f58accb7eb293b550fa59618674b7d",
|
||||
:rs_host => "http://rs.qiniu.com",
|
||||
:fetch_host => "http://iovip.qbox.me",
|
||||
:rsf_host => "http://rsf.qbox.me",
|
||||
:up_host => "http://up.qiniu.com",
|
||||
:pub_host => "http://pu.qbox.me:10200",
|
||||
:eu_host => "http://eu.qbox.me",
|
||||
:access_key => "",
|
||||
:secret_key => "",
|
||||
:auto_reconnect => true,
|
||||
:max_retry_times => 5
|
||||
:max_retry_times => 3,
|
||||
:block_size => 1024*1024*4,
|
||||
:chunk_size => 1024*256,
|
||||
:enable_debug => true,
|
||||
:tmpdir => Dir.tmpdir + File::SEPARATOR + 'QiniuRuby'
|
||||
}
|
||||
|
||||
REQUIRED_OPTION_KEYS = [:client_id, :client_secret, :auth_url, :rs_host, :io_host]
|
||||
REQUIRED_OPTION_KEYS = [:access_key, :secret_key, :up_host]
|
||||
|
||||
attr_reader :settings, :default_params
|
||||
|
||||
def load config_file
|
||||
if File.exist?(config_file)
|
||||
config_options = YAML.load_file(config_file)
|
||||
config_options.symbolize_keys!
|
||||
initialize_connect(config_options)
|
||||
else
|
||||
raise MissingConfError, config_file
|
||||
@@ -46,13 +50,12 @@ module Qiniu
|
||||
end
|
||||
|
||||
def initialize_connect options = {}
|
||||
@settings = DEFAULT_OPTIONS.merge(options)
|
||||
@settings = DEFAULT_OPTIONS.merge!(options)
|
||||
REQUIRED_OPTION_KEYS.each do |opt|
|
||||
raise MissingArgsError, [opt] unless @settings.has_key?(opt)
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end # module Config
|
||||
end # module Qiniu
|
||||
@@ -1,12 +1,8 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
module Qiniu
|
||||
module RS
|
||||
|
||||
class Exception < RuntimeError
|
||||
def to_s
|
||||
inspect
|
||||
end
|
||||
end
|
||||
|
||||
class ResponseError < Exception
|
||||
@@ -32,7 +28,7 @@ module Qiniu
|
||||
|
||||
class RequestFailed < ResponseError
|
||||
def message
|
||||
"HTTP status code #{http_code}"
|
||||
"HTTP status code: #{http_code}. Response body: #{http_body}"
|
||||
end
|
||||
|
||||
def to_s
|
||||
@@ -40,6 +36,43 @@ module Qiniu
|
||||
end
|
||||
end
|
||||
|
||||
class UploadFailedError < Exception
|
||||
def initialize(status_code, response_data)
|
||||
data_string = response_data.map { |key, value| %Q(:#{key.to_s} => #{value.to_s}) }
|
||||
msg = %Q(Uploading Failed. HTTP Status Code: #{status_code}. HTTP response body: #{data_string.join(', ')}.)
|
||||
super(msg)
|
||||
end
|
||||
end
|
||||
|
||||
class FileSeekReadError < Exception
|
||||
def initialize(fpath, block_index, seek_pos, read_length, result_length)
|
||||
msg = "Reading file: #{fpath}, "
|
||||
msg += "at block index: #{block_index}. "
|
||||
msg += "Expected seek_pos:#{seek_pos} and read_length:#{read_length}, "
|
||||
msg += "but got result_length: #{result_length}."
|
||||
super(msg)
|
||||
end
|
||||
end
|
||||
|
||||
class BlockSizeNotMathchError < Exception
|
||||
def initialize(fpath, block_index, offset, restsize, block_size)
|
||||
msg = "Reading file: #{fpath}, "
|
||||
msg += "at block index: #{block_index}. "
|
||||
msg += "Expected offset: #{offset}, restsize: #{restsize} and block_size: #{block_size}, "
|
||||
msg += "but got offset+restsize=#{offset+restsize}."
|
||||
super(msg)
|
||||
end
|
||||
end
|
||||
|
||||
class BlockCountNotMathchError < Exception
|
||||
def initialize(fpath, block_count, checksum_count, progress_count)
|
||||
msg = "Reading file: #{fpath}, "
|
||||
msg += "Expected block_count, checksum_count, progress_count is: #{block_count}, "
|
||||
msg += "but got checksum_count: #{checksum_count}, progress_count: #{progress_count}."
|
||||
super(msg)
|
||||
end
|
||||
end
|
||||
|
||||
class MissingArgsError < Exception
|
||||
def initialize(missing_keys)
|
||||
key_list = missing_keys.map {|key| key.to_s}.join(' and the ')
|
||||
@@ -84,5 +117,4 @@ module Qiniu
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end # module Qiniu
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'qiniu/image'
|
||||
require 'qiniu/pfop'
|
||||
Executable
+137
@@ -0,0 +1,137 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
# vim: sw=2 ts=2
|
||||
|
||||
module Qiniu
|
||||
module HTTP
|
||||
|
||||
class << self
|
||||
public
|
||||
def is_response_ok?(http_code)
|
||||
return 200 <= http_code && http_code <= 299
|
||||
end # is_response_ok?
|
||||
|
||||
def generate_query_string(params)
|
||||
if params.is_a?(Hash)
|
||||
total_param = params.map { |key, value| %Q(#{CGI.escape(key.to_s)}=#{CGI.escape(value.to_s).gsub('+', '%20')}) }
|
||||
return total_param.join("&")
|
||||
end
|
||||
|
||||
return params
|
||||
end # generate_query_string
|
||||
|
||||
def get (url, opts = {})
|
||||
### 配置请求Header
|
||||
req_headers = {
|
||||
:connection => 'close',
|
||||
:accept => '*/*',
|
||||
:user_agent => Config.settings[:user_agent]
|
||||
}
|
||||
|
||||
# 优先使用外部Header,覆盖任何特定Header
|
||||
if opts[:headers].is_a?(Hash) then
|
||||
req_headers.merge!(opts[:headers])
|
||||
end
|
||||
|
||||
### 发送请求
|
||||
response = RestClient.get(url, req_headers)
|
||||
return response.code.to_i, response.body, response.raw_headers
|
||||
rescue => e
|
||||
Log.logger.warn "#{e.message} => Qiniu::HTTP.get('#{url}')"
|
||||
if e.respond_to?(:response) && e.response.respond_to?(:code) then
|
||||
return e.response.code, e.response.body, e.response.raw_headers
|
||||
end
|
||||
return nil, nil, nil
|
||||
end # get
|
||||
|
||||
API_RESULT_MIMETYPE = 'application/json'
|
||||
|
||||
def api_get (url, opts = {})
|
||||
### 配置请求Header
|
||||
headers = {
|
||||
:accept => API_RESULT_MIMETYPE
|
||||
}
|
||||
|
||||
# 将特定Header混入外部Header中
|
||||
if opts[:headers].is_a?(Hash) then
|
||||
opts[:headers] = opts[:headers].dup.merge!(headers)
|
||||
else
|
||||
opts[:headers] = headers
|
||||
end
|
||||
|
||||
### 发送请求,然后转换返回值
|
||||
resp_code, resp_body, resp_headers = get(url, opts)
|
||||
if resp_code.nil? then
|
||||
return 0, {}, {}
|
||||
end
|
||||
|
||||
content_type = resp_headers["content-type"][0]
|
||||
if !content_type.nil? && !content_type.downcase.index(API_RESULT_MIMETYPE).nil? then
|
||||
# 如果是JSON格式,则反序列化
|
||||
resp_body = Utils.safe_json_parse(resp_body)
|
||||
end
|
||||
|
||||
return resp_code, resp_body, resp_headers
|
||||
end # api_get
|
||||
|
||||
def post (url, req_body = nil, opts = {})
|
||||
### 配置请求Header
|
||||
req_headers = {
|
||||
:connection => 'close',
|
||||
:accept => '*/*',
|
||||
:user_agent => Config.settings[:user_agent]
|
||||
}
|
||||
|
||||
# 优先使用外部Header,覆盖任何特定Header
|
||||
if opts[:headers].is_a?(Hash) then
|
||||
req_headers.merge!(opts[:headers])
|
||||
end
|
||||
|
||||
### 发送请求
|
||||
response = RestClient.post(url, req_body, req_headers)
|
||||
return response.code.to_i, response.body, response.raw_headers
|
||||
rescue => e
|
||||
Log.logger.warn "#{e.message} => Qiniu::HTTP.post('#{url}')"
|
||||
if e.respond_to?(:response) && e.response.respond_to?(:code) then
|
||||
return e.response.code, e.response.body, e.response.raw_headers
|
||||
end
|
||||
return nil, nil, nil
|
||||
end # post
|
||||
|
||||
def api_post (url, req_body = nil, opts = {})
|
||||
### 配置请求Header
|
||||
headers = {
|
||||
:accept => API_RESULT_MIMETYPE
|
||||
}
|
||||
|
||||
# 将特定Header混入外部Header中
|
||||
if opts[:headers].is_a?(Hash) then
|
||||
opts[:headers] = opts[:headers].dup.merge!(headers)
|
||||
else
|
||||
opts[:headers] = headers
|
||||
end
|
||||
|
||||
### 发送请求,然后转换返回值
|
||||
resp_code, resp_body, resp_headers = post(url, req_body, opts)
|
||||
if resp_code.nil? then
|
||||
return 0, {}, {}
|
||||
end
|
||||
|
||||
content_type = resp_headers["content-type"][0]
|
||||
if !content_type.nil? && !content_type.downcase.index(API_RESULT_MIMETYPE).nil? then
|
||||
# 如果是JSON格式,则反序列化
|
||||
resp_body = Utils.safe_json_parse(resp_body)
|
||||
end
|
||||
|
||||
return resp_code, resp_body, resp_headers
|
||||
end # api_post
|
||||
|
||||
def management_post (url, body = '')
|
||||
### 授权并执行管理操作
|
||||
return HTTP.api_post(url, body, {
|
||||
:headers => { 'Authorization' => 'QBox ' + Auth.generate_acctoken(url, body) }
|
||||
})
|
||||
end # management_post
|
||||
end # class << self
|
||||
|
||||
end # module HTTP
|
||||
end # module Qiniu
|
||||
Executable
+38
@@ -0,0 +1,38 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
module Qiniu
|
||||
module Fop
|
||||
module Image
|
||||
class << self
|
||||
include Utils
|
||||
|
||||
def info(url)
|
||||
return HTTP.api_get(url + '?imageInfo')
|
||||
end # info
|
||||
|
||||
def exif(url)
|
||||
return HTTP.api_get(url + '?exif')
|
||||
end # exif
|
||||
|
||||
def mogrify_preview_url(source_image_url, options)
|
||||
source_image_url + '?' + generate_mogrify_params_string(options)
|
||||
end
|
||||
|
||||
def generate_mogrify_params_string(options = {})
|
||||
opts = {}
|
||||
options.each do |k, v|
|
||||
opts[k.to_s] = v
|
||||
end
|
||||
params_string = ""
|
||||
keys = ["thumbnail", "gravity", "crop", "quality", "rotate", "format"]
|
||||
keys.each do |key|
|
||||
params_string += %Q(/#{key}/#{opts[key]}) unless opts[key].nil?
|
||||
end
|
||||
params_string += '/auto-orient' unless opts["auto_orient"].nil?
|
||||
'imageMogr' + URI.escape(params_string)
|
||||
end
|
||||
|
||||
end
|
||||
end # module Image
|
||||
end # module Fop
|
||||
end # module Qiniu
|
||||
@@ -3,7 +3,6 @@
|
||||
require 'logger'
|
||||
|
||||
module Qiniu
|
||||
module RS
|
||||
module Log
|
||||
class << self
|
||||
attr_accessor :logger
|
||||
@@ -12,6 +11,5 @@ module Qiniu
|
||||
@logger ||= Logger.new(STDERR)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end # module Log
|
||||
end # module Qiniu
|
||||
Executable
+171
@@ -0,0 +1,171 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
# vim: sw=2 ts=2
|
||||
|
||||
require 'qiniu/adt'
|
||||
require 'qiniu/http'
|
||||
|
||||
module Qiniu
|
||||
module Storage
|
||||
class ListPolicy
|
||||
include ADT::Policy
|
||||
|
||||
private
|
||||
def initialize(bucket,
|
||||
limit = 1000,
|
||||
prefix = '',
|
||||
delimiter = '')
|
||||
@bucket = bucket
|
||||
@limit = limit
|
||||
@prefix = prefix
|
||||
@delimiter = delimiter
|
||||
end # initialize
|
||||
|
||||
public
|
||||
PARAMS = {
|
||||
# 字符串类型参数
|
||||
:bucket => "bucket",
|
||||
:prefix => "prefix",
|
||||
:delimiter => "delimiter",
|
||||
:marker => "marker",
|
||||
|
||||
# 数值类型参数
|
||||
:limit => "limit"
|
||||
} # PARAMS
|
||||
|
||||
PARAMS.each_pair do |key, fld|
|
||||
attr_accessor key
|
||||
end
|
||||
|
||||
def params
|
||||
return PARAMS
|
||||
end # params
|
||||
|
||||
alias :to_s :to_query_string
|
||||
end # class ListPolicy
|
||||
|
||||
class << self
|
||||
include Utils
|
||||
|
||||
public
|
||||
def buckets
|
||||
url = Config.settings[:rs_host] + '/buckets'
|
||||
return HTTP.management_post(url)
|
||||
end # buckets
|
||||
|
||||
def stat(bucket, key)
|
||||
url = Config.settings[:rs_host] + '/stat/' + encode_entry_uri(bucket, key)
|
||||
return HTTP.management_post(url)
|
||||
end # stat
|
||||
|
||||
def get(bucket, key, save_as = nil, expires_in = nil, version = nil)
|
||||
url = Config.settings[:rs_host] + '/get/' + encode_entry_uri(bucket, key)
|
||||
url += '/base/' + version unless version.nil?
|
||||
url += '/attName/' + Utils.urlsafe_base64_encode(save_as) unless save_as.nil?
|
||||
url += '/expires/' + expires_in.to_s if !expires_in.nil? && expires_in > 0
|
||||
return HTTP.management_post(url)
|
||||
end # get
|
||||
|
||||
def copy(source_bucket, source_key, target_bucket, target_key)
|
||||
uri = _generate_cp_or_mv_opstr('copy', source_bucket, source_key, target_bucket, target_key)
|
||||
url = Config.settings[:rs_host] + uri
|
||||
return HTTP.management_post(url)
|
||||
end # copy
|
||||
|
||||
def move(source_bucket, source_key, target_bucket, target_key)
|
||||
uri = _generate_cp_or_mv_opstr('move', source_bucket, source_key, target_bucket, target_key)
|
||||
url = Config.settings[:rs_host] + uri
|
||||
return HTTP.management_post(url)
|
||||
end # move
|
||||
|
||||
def delete(bucket, key)
|
||||
url = Config.settings[:rs_host] + '/delete/' + encode_entry_uri(bucket, key)
|
||||
return HTTP.management_post(url)
|
||||
end # delete
|
||||
|
||||
def fetch(bucket, target_url, key)
|
||||
url = Config.settings[:fetch_host] + '/fetch/' + Utils.urlsafe_base64_encode(target_url) + '/to/' + encode_entry_uri(bucket, key)
|
||||
return HTTP.management_post(url)
|
||||
end # fetch
|
||||
|
||||
def batch(command, bucket, keys)
|
||||
execs = []
|
||||
keys.each do |key|
|
||||
encoded_uri = encode_entry_uri(bucket, key)
|
||||
execs << "op=/#{command}/#{encoded_uri}"
|
||||
end
|
||||
url = Config.settings[:rs_host] + "/batch"
|
||||
return HTTP.management_post(url, execs.join("&"))
|
||||
end # batch
|
||||
|
||||
def batch_get(bucket, keys)
|
||||
batch("get", bucket, keys)
|
||||
end # batch_get
|
||||
|
||||
def batch_stat(bucket, keys)
|
||||
batch("stat", bucket, keys)
|
||||
end # batch_stat
|
||||
|
||||
def batch_copy(*args)
|
||||
_batch_cp_or_mv('copy', args)
|
||||
end # batch_copy
|
||||
|
||||
def batch_move(*args)
|
||||
_batch_cp_or_mv('move', args)
|
||||
end # batch_move
|
||||
|
||||
def batch_delete(bucket, keys)
|
||||
batch("delete", bucket, keys)
|
||||
end # batch_delete
|
||||
|
||||
def save_as(bucket, key, source_url, op_params_string)
|
||||
encoded_uri = encode_entry_uri(bucket, key)
|
||||
save_as_string = '/save-as/' + encoded_uri
|
||||
new_url = source_url + '?' + op_params_string + save_as_string
|
||||
return HTTP.management_post(new_url)
|
||||
end # save_as
|
||||
|
||||
def image_mogrify_save_as(bucket, key, source_image_url, options)
|
||||
mogrify_params_string = Fop::Image.generate_mogrify_params_string(options)
|
||||
save_as(bucket, key, source_image_url, mogrify_params_string)
|
||||
end # image_mogrify_save_as
|
||||
|
||||
def list(list_policy)
|
||||
url = Config.settings[:rsf_host] + '/list?' + list_policy.to_query_string()
|
||||
|
||||
resp_code, resp_body, resp_headers = HTTP.management_post(url)
|
||||
if resp_code == 0 || resp_code > 299 then
|
||||
has_more = false
|
||||
return resp_code, resp_body, resp_headers, has_more, list_policy
|
||||
end
|
||||
|
||||
has_more = (resp_body['marker'].is_a?(String) && resp_body['marker'] != '')
|
||||
if has_more then
|
||||
new_list_policy = list_policy.clone()
|
||||
new_list_policy.marker = resp_body['marker']
|
||||
else
|
||||
new_list_policy = list_policy
|
||||
end
|
||||
|
||||
return resp_code, resp_body, resp_headers, has_more, new_list_policy
|
||||
end # list
|
||||
|
||||
private
|
||||
|
||||
def _generate_cp_or_mv_opstr(command, source_bucket, source_key, target_bucket, target_key)
|
||||
source_encoded_entry_uri = encode_entry_uri(source_bucket, source_key)
|
||||
target_encoded_entry_uri = encode_entry_uri(target_bucket, target_key)
|
||||
%Q(/#{command}/#{source_encoded_entry_uri}/#{target_encoded_entry_uri})
|
||||
end # _generate_cp_or_mv_opstr
|
||||
|
||||
def _batch_cp_or_mv(command, *op_args)
|
||||
execs = []
|
||||
op_args.each do |e|
|
||||
execs << 'op=' + _generate_cp_or_mv_opstr(command, e[0], e[1], e[2], e[3]) if e.size == 4
|
||||
end
|
||||
url = Config.settings[:rs_host] + "/batch"
|
||||
return HTTP.management_post(url, execs.join("&"))
|
||||
end # _batch_cp_or_mv
|
||||
|
||||
end # class << self
|
||||
end # module Storage
|
||||
end # module Qiniu
|
||||
Executable
+35
@@ -0,0 +1,35 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'qiniu/http'
|
||||
|
||||
module Qiniu
|
||||
module Misc
|
||||
class << self
|
||||
def set_protected(bucket, protected_mode)
|
||||
url = Config.settings[:pub_host] + %Q(/accessMode/#{bucket}/mode/#{protected_mode})
|
||||
return HTTP.management_post(url)
|
||||
end # set_protected
|
||||
|
||||
def set_separator(bucket, separator)
|
||||
encoded_separator = Utils.urlsafe_base64_encode(separator)
|
||||
url = Config.settings[:pub_host] + %Q(/separator/#{bucket}/sep/#{encoded_separator})
|
||||
return HTTP.management_post(url)
|
||||
end # set_separator
|
||||
|
||||
def set_style(bucket, name, style)
|
||||
encoded_name = Utils.urlsafe_base64_encode(name)
|
||||
encoded_style = Utils.urlsafe_base64_encode(style)
|
||||
url = Config.settings[:pub_host] + %Q(/style/#{bucket}/name/#{encoded_name}/style/#{encoded_style})
|
||||
return HTTP.management_post(url)
|
||||
end # set_style
|
||||
|
||||
def unset_style(bucket, name)
|
||||
encoded_name = Utils.urlsafe_base64_encode(name)
|
||||
url = Config.settings[:pub_host] + %Q(/unstyle/#{bucket}/name/#{encoded_name})
|
||||
return HTTP.management_post(url)
|
||||
end # unset_style
|
||||
end # class << self
|
||||
|
||||
end # module Misc
|
||||
end # module Qiniu
|
||||
|
||||
Executable
+124
@@ -0,0 +1,124 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
# vim: sw=2 ts=2
|
||||
|
||||
require 'qiniu/adt'
|
||||
require 'qiniu/http'
|
||||
|
||||
module Qiniu
|
||||
module Fop
|
||||
module Persistance
|
||||
|
||||
class PfopPolicy
|
||||
include ADT::Policy
|
||||
|
||||
private
|
||||
def initialize(bucket,
|
||||
key,
|
||||
fops,
|
||||
notify_url)
|
||||
@bucket = bucket
|
||||
@key = key
|
||||
@notify_url = notify_url
|
||||
|
||||
self.fops!(fops)
|
||||
end # initialize
|
||||
|
||||
public
|
||||
PARAMS = {
|
||||
# 字符串类型参数
|
||||
:bucket => "bucket",
|
||||
:key => "key",
|
||||
:fops => "fops",
|
||||
:notify_url => "notifyURL",
|
||||
:pipeline => "pipeline",
|
||||
|
||||
# 数值类型参数
|
||||
:force => "force"
|
||||
} # PARAMS
|
||||
|
||||
PARAMS.each_pair do |key, fld|
|
||||
attr_accessor key
|
||||
end
|
||||
|
||||
def params
|
||||
return PARAMS
|
||||
end # params
|
||||
|
||||
def fops! (fops)
|
||||
if fops.is_a?(Hash) then
|
||||
fops = fops.values
|
||||
end
|
||||
|
||||
if fops.is_a?(Array) then
|
||||
new_fops = []
|
||||
fops.each do |v|
|
||||
if v.is_a?(ApiSpecification) then
|
||||
new_fops.push(v.to_s)
|
||||
end
|
||||
end
|
||||
|
||||
@fops = new_fops.join(";")
|
||||
else
|
||||
@fops = fops.to_s
|
||||
end
|
||||
end # fops!
|
||||
|
||||
def force!
|
||||
@force = 1
|
||||
end # force!
|
||||
|
||||
alias :to_s :to_json
|
||||
end # class PfopPolicy
|
||||
|
||||
class << self
|
||||
|
||||
API_HOST = 'http://api.qiniu.com'
|
||||
|
||||
PFOP_URL = API_HOST + '/pfop/'
|
||||
|
||||
def pfop (args)
|
||||
### 生成fop指令串
|
||||
if args.is_a?(PfopPolicy) then
|
||||
# PfopPolicy的各个字段按固定顺序组织
|
||||
body = args.to_query_string()
|
||||
elsif args.is_a?(Hash) then
|
||||
# 无法保证固定字段顺序
|
||||
body = HTTP.generate_query_string(args)
|
||||
else
|
||||
# 由调用者保证固定字段顺序
|
||||
body = args.to_s
|
||||
end
|
||||
|
||||
### 发送请求
|
||||
return HTTP.management_post(PFOP_URL, body)
|
||||
end # pfop
|
||||
|
||||
PREFOP_URL = API_HOST + '/status/get/prefop?id='
|
||||
|
||||
def prefop (persistent_id)
|
||||
### 抽取persistentId
|
||||
if persistent_id.is_a?(Hash) then
|
||||
pid = persistent_id['persistentId']
|
||||
else
|
||||
pid = persistent_id.to_s
|
||||
end
|
||||
|
||||
### 发送请求
|
||||
url = PREFOP_URL + pid
|
||||
return HTTP.api_get(url)
|
||||
end # prefop
|
||||
|
||||
def generate_p1_url (url, fop)
|
||||
# 如果fop是ApiSpecification,则各字段按固定顺序组织,保证一致性
|
||||
# 否则由调用者保证固定字段顺序
|
||||
fop = CGI.escape(fop.to_s).gsub('+', '%20')
|
||||
|
||||
### 生成url
|
||||
return url + '?p/1/' + fop
|
||||
end # generate_pl_url
|
||||
|
||||
end # class << self
|
||||
|
||||
end # module Persistance
|
||||
end # module Fop
|
||||
end # module Qiniu
|
||||
Executable
+319
@@ -0,0 +1,319 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'zlib'
|
||||
require 'yaml'
|
||||
require 'tmpdir'
|
||||
require 'fileutils'
|
||||
require 'mime/types'
|
||||
require 'digest/sha1'
|
||||
require 'qiniu/abstract'
|
||||
require 'qiniu/exceptions'
|
||||
|
||||
module Qiniu
|
||||
module Storage
|
||||
|
||||
module AbstractClass
|
||||
class ChunkProgressNotifier
|
||||
include Qiniu::Abstract
|
||||
abstract_methods :notify
|
||||
# def notify(block_index, block_put_progress); end
|
||||
end
|
||||
|
||||
class BlockProgressNotifier
|
||||
include Qiniu::Abstract
|
||||
abstract_methods :notify
|
||||
# def notify(block_index, checksum); end
|
||||
end
|
||||
end # module AbstractClass
|
||||
|
||||
class ChunkProgressNotifier < AbstractClass::ChunkProgressNotifier
|
||||
def notify(index, progress)
|
||||
logmsg = "chunk #{progress[:offset]/Config.settings[:chunk_size]} in block #{index} successfully uploaded.\n" + progress.to_s
|
||||
Utils.debug(logmsg)
|
||||
end
|
||||
end # class ChunkProgressNotifier
|
||||
|
||||
class BlockProgressNotifier < AbstractClass::BlockProgressNotifier
|
||||
def notify(index, checksum)
|
||||
Utils.debug "block #{index}: {ctx: #{checksum}} successfully uploaded."
|
||||
Utils.debug "block #{index}: {checksum: #{checksum}} successfully uploaded."
|
||||
end
|
||||
end # class BlockProgressNotifier
|
||||
|
||||
class << self
|
||||
include Utils
|
||||
|
||||
def resumable_upload_with_token(uptoken,
|
||||
local_file,
|
||||
bucket,
|
||||
key = nil,
|
||||
mime_type = nil,
|
||||
custom_meta = nil,
|
||||
customer = nil,
|
||||
callback_params = nil,
|
||||
rotate = nil)
|
||||
begin
|
||||
ifile = File.open(local_file, 'rb')
|
||||
fh = FileData.new(ifile)
|
||||
fsize = fh.data_size
|
||||
key = Digest::SHA1.hexdigest(local_file + fh.mtime.to_s) if key.nil?
|
||||
if mime_type.nil? || mime_type.empty?
|
||||
mime = MIME::Types.type_for local_file
|
||||
mime_type = mime.empty? ? 'application/octet-stream' : mime[0].content_type
|
||||
end
|
||||
code, data = _resumable_upload(uptoken, fh, fsize, bucket, key, mime_type, custom_meta, customer, callback_params, rotate)
|
||||
[code, data]
|
||||
ensure
|
||||
ifile.close unless ifile.nil?
|
||||
end
|
||||
end # resumable_upload_with_token
|
||||
|
||||
private
|
||||
|
||||
class FileData
|
||||
attr_accessor :fh
|
||||
def initialize(fh)
|
||||
@fh = fh
|
||||
end
|
||||
def data_size
|
||||
@fh.stat.size
|
||||
end
|
||||
def get_data(offset, length)
|
||||
@fh.seek(offset)
|
||||
@fh.read(length)
|
||||
end
|
||||
def path
|
||||
@fh.path
|
||||
end
|
||||
def mtime
|
||||
@fh.mtime
|
||||
end
|
||||
#delegate :path, :mtime, :to => :fh
|
||||
end # class FileData
|
||||
|
||||
def _new_block_put_progress_data
|
||||
{:ctx => nil, :offset => 0, :restsize => nil, :status_code => nil, :host => nil}
|
||||
end # _new_block_put_progress_data
|
||||
|
||||
def _call_binary_with_token(uptoken, url, data, content_type = nil, retry_times = 0)
|
||||
options = {
|
||||
:headers => {
|
||||
:content_type => 'application/octet-stream',
|
||||
'Authorization' => 'UpToken ' + uptoken
|
||||
}
|
||||
}
|
||||
if !content_type.nil? && !content_type.empty? then
|
||||
options[:headers][:content_type] = content_type
|
||||
end
|
||||
|
||||
code, data, raw_headers = HTTP.api_post(url, data, options)
|
||||
unless HTTP.is_response_ok?(code)
|
||||
retry_times += 1
|
||||
if Config.settings[:auto_reconnect] && retry_times < Config.settings[:max_retry_times]
|
||||
return _call_binary_with_token(uptoken, url, data, options[:content_type], retry_times)
|
||||
end
|
||||
end
|
||||
return code, data, raw_headers
|
||||
end # _call_binary_with_token
|
||||
|
||||
def _mkblock(uptoken, block_size, body)
|
||||
url = Config.settings[:up_host] + "/mkblk/#{block_size}"
|
||||
_call_binary_with_token(uptoken, url, body)
|
||||
end # _mkblock
|
||||
|
||||
def _putblock(uphost, uptoken, ctx, offset, body)
|
||||
url = uphost + "/bput/#{ctx}/#{offset}"
|
||||
_call_binary_with_token(uptoken, url, body)
|
||||
end # _putblock
|
||||
|
||||
def _resumable_put_block(uptoken,
|
||||
fh,
|
||||
block_index,
|
||||
block_size,
|
||||
chunk_size,
|
||||
progress,
|
||||
retry_times,
|
||||
notifier)
|
||||
code, data = 0, {}
|
||||
fpath = fh.path
|
||||
|
||||
# this block has never been uploaded.
|
||||
if progress[:ctx] == nil || progress[:ctx].empty?
|
||||
progress[:offset] = 0
|
||||
progress[:restsize] = block_size
|
||||
# choose the smaller one
|
||||
body_length = [block_size, chunk_size].min
|
||||
for i in 1..retry_times
|
||||
seek_pos = block_index*Config.settings[:block_size]
|
||||
body = fh.get_data(seek_pos, body_length)
|
||||
result_length = body.length
|
||||
if result_length != body_length
|
||||
raise FileSeekReadError.new(fpath, block_index, seek_pos, body_length, result_length)
|
||||
end
|
||||
|
||||
code, data, raw_headers = _mkblock(uptoken, block_size, body)
|
||||
Utils.debug "Mkblk : #{code.inspect} #{data.inspect} #{raw_headers.inspect}"
|
||||
|
||||
body_crc32 = Zlib.crc32(body)
|
||||
if HTTP.is_response_ok?(code) && data["crc32"] == body_crc32
|
||||
progress[:ctx] = data["ctx"]
|
||||
progress[:offset] = body_length
|
||||
progress[:restsize] = block_size - body_length
|
||||
progress[:status_code] = code
|
||||
progress[:host] = data["host"]
|
||||
if !notifier.nil? && notifier.respond_to?("notify")
|
||||
notifier.notify(block_index, progress)
|
||||
end
|
||||
break
|
||||
elsif i == retry_times && data["crc32"] != body_crc32
|
||||
Log.logger.error %Q(Uploading block error. Expected crc32: #{body_crc32}, but got: #{data["crc32"]})
|
||||
return code, data, raw_headers
|
||||
end
|
||||
end
|
||||
elsif progress[:offset] + progress[:restsize] != block_size
|
||||
raise BlockSizeNotMathchError.new(fpath, block_index, progress[:offset], progress[:restsize], block_size)
|
||||
end
|
||||
|
||||
# loop uploading other chunks except the first one
|
||||
while progress[:restsize].to_i > 0 && progress[:restsize] < block_size
|
||||
# choose the smaller one
|
||||
body_length = [progress[:restsize], chunk_size].min
|
||||
for i in 1..retry_times
|
||||
seek_pos = block_index*Config.settings[:block_size] + progress[:offset]
|
||||
body = fh.get_data(seek_pos, body_length)
|
||||
result_length = body.length
|
||||
if result_length != body_length
|
||||
raise FileSeekReadError.new(fpath, block_index, seek_pos, body_length, result_length)
|
||||
end
|
||||
|
||||
code, data, raw_headers = _putblock(progress[:host], uptoken, progress[:ctx], progress[:offset], body)
|
||||
Utils.debug "Bput : #{code.inspect} #{data.inspect} #{raw_headers.inspect}"
|
||||
|
||||
body_crc32 = Zlib.crc32(body)
|
||||
if HTTP.is_response_ok?(code) && data["crc32"] == body_crc32
|
||||
progress[:ctx] = data["ctx"]
|
||||
progress[:offset] += body_length
|
||||
progress[:restsize] -= body_length
|
||||
progress[:status_code] = code
|
||||
progress[:host] = data["host"]
|
||||
if !notifier.nil? && notifier.respond_to?("notify")
|
||||
notifier.notify(block_index, progress)
|
||||
end
|
||||
break
|
||||
elsif i == retry_times && data["crc32"] != body_crc32
|
||||
Log.logger.error %Q(Uploading block error. Expected crc32: #{body_crc32}, but got: #{data["crc32"]})
|
||||
return code, data, raw_headers
|
||||
end
|
||||
end
|
||||
end
|
||||
# return
|
||||
return code, data, raw_headers
|
||||
end # _resumable_put_block
|
||||
|
||||
def _block_count(fsize)
|
||||
((fsize + Config.settings[:block_size] - 1) / Config.settings[:block_size]).to_i
|
||||
end # _block_count
|
||||
|
||||
def _resumable_put(uptoken,
|
||||
fh,
|
||||
checksums,
|
||||
progresses,
|
||||
block_notifier = nil,
|
||||
chunk_notifier = nil)
|
||||
code, data = 0, {}
|
||||
fsize = fh.data_size
|
||||
block_count = _block_count(fsize)
|
||||
checksum_count = checksums.length
|
||||
progress_count = progresses.length
|
||||
if checksum_count != block_count || progress_count != block_count
|
||||
raise BlockCountNotMathchError.new(fh.path, block_count, checksum_count, progress_count)
|
||||
end
|
||||
0.upto(block_count-1).each do |block_index|
|
||||
if checksums[block_index].nil? || checksums[block_index].empty?
|
||||
block_size = Config.settings[:block_size]
|
||||
if block_index == block_count - 1
|
||||
block_size = fsize - block_index*Config.settings[:block_size]
|
||||
end
|
||||
if progresses[block_index].nil?
|
||||
progresses[block_index] = _new_block_put_progress_data
|
||||
end
|
||||
#code, data = _resumable_put_block(uptoken, fh, block_index, block_size, Config.settings[:chunk_size], progresses[block_index], Config.settings[:max_retry_times], chunk_notifier)
|
||||
# Put the whole block as a chunk
|
||||
code, data = _resumable_put_block(uptoken, fh, block_index, block_size, block_size, progresses[block_index], Config.settings[:max_retry_times], chunk_notifier)
|
||||
if HTTP.is_response_ok?(code)
|
||||
#checksums[block_index] = data["checksum"]
|
||||
checksums[block_index] = data["ctx"]
|
||||
if !block_notifier.nil? && block_notifier.respond_to?("notify")
|
||||
block_notifier.notify(block_index, checksums[block_index])
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return [code, data]
|
||||
end # _resumable_put
|
||||
|
||||
def _mkfile(uphost,
|
||||
uptoken,
|
||||
entry_uri,
|
||||
fsize,
|
||||
checksums,
|
||||
mime_type = nil,
|
||||
custom_meta = nil,
|
||||
customer = nil,
|
||||
callback_params = nil,
|
||||
rotate = nil)
|
||||
path = '/rs-mkfile/' + Utils.urlsafe_base64_encode(entry_uri) + "/fsize/#{fsize}"
|
||||
path += '/mimeType/' + Utils.urlsafe_base64_encode(mime_type) if !mime_type.nil? && !mime_type.empty?
|
||||
path += '/meta/' + Utils.urlsafe_base64_encode(custom_meta) if !custom_meta.nil? && !custom_meta.empty?
|
||||
path += '/customer/' + customer if !customer.nil? && !customer.empty?
|
||||
callback_query_string = HTTP.generate_query_string(callback_params) if !callback_params.nil? && !callback_params.empty?
|
||||
path += '/params/' + Utils.urlsafe_base64_encode(callback_query_string) if !callback_query_string.nil? && !callback_query_string.empty?
|
||||
path += '/rotate/' + rotate if !rotate.nil? && rotate.to_i >= 0
|
||||
url = uphost + path
|
||||
#body = ''
|
||||
#checksums.each do |checksum|
|
||||
# body += Utils.urlsafe_base64_decode(checksum)
|
||||
#end
|
||||
body = checksums.join(',')
|
||||
_call_binary_with_token(uptoken, url, body, 'text/plain')
|
||||
end # _mkfile
|
||||
|
||||
def _resumable_upload(uptoken,
|
||||
fh,
|
||||
fsize,
|
||||
bucket,
|
||||
key,
|
||||
mime_type = nil,
|
||||
custom_meta = nil,
|
||||
customer = nil,
|
||||
callback_params = nil,
|
||||
rotate = nil)
|
||||
|
||||
block_count = _block_count(fsize)
|
||||
|
||||
chunk_notifier = ChunkProgressNotifier.new()
|
||||
block_notifier = BlockProgressNotifier.new()
|
||||
|
||||
progresses = []
|
||||
block_count.times{progresses << _new_block_put_progress_data}
|
||||
checksums = []
|
||||
block_count.times{checksums << ''}
|
||||
|
||||
code, data, raw_headers = _resumable_put(uptoken, fh, checksums, progresses, block_notifier, chunk_notifier)
|
||||
|
||||
if HTTP.is_response_ok?(code)
|
||||
uphost = data["host"]
|
||||
entry_uri = bucket + ':' + key
|
||||
code, data, raw_headers = _mkfile(uphost, uptoken, entry_uri, fsize, checksums, mime_type, custom_meta, customer, callback_params, rotate)
|
||||
Utils.debug "Mkfile : #{code.inspect} #{data.inspect} #{raw_headers.inspect}"
|
||||
end
|
||||
|
||||
if HTTP.is_response_ok?(code)
|
||||
Utils.debug "File #{fh.path} {size: #{fsize}} successfully uploaded."
|
||||
end
|
||||
|
||||
return code, data, raw_headers
|
||||
end # _resumable_upload
|
||||
end # self class
|
||||
end # module Storage
|
||||
end # module Qiniu
|
||||
-121
@@ -1,121 +0,0 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'qiniu/rs/version'
|
||||
|
||||
module Qiniu
|
||||
module RS
|
||||
autoload :Config, 'qiniu/rs/config'
|
||||
autoload :Log, 'qiniu/rs/log'
|
||||
autoload :Exception, 'qiniu/rs/exceptions'
|
||||
autoload :Utils, 'qiniu/rs/utils'
|
||||
autoload :Auth, 'qiniu/rs/auth'
|
||||
autoload :IO, 'qiniu/rs/io'
|
||||
autoload :RS, 'qiniu/rs/rs'
|
||||
autoload :Image, 'qiniu/rs/image'
|
||||
|
||||
class << self
|
||||
|
||||
StatusOK = 200
|
||||
|
||||
def establish_connection!(opts = {})
|
||||
Config.initialize_connect opts
|
||||
end
|
||||
|
||||
def login!(user, pwd)
|
||||
code, data = Auth.exchange_by_password!(user, pwd)
|
||||
code == StatusOK
|
||||
end
|
||||
|
||||
def put_auth(expires_in = nil, callback_url = nil)
|
||||
code, data = IO.put_auth(expires_in, callback_url)
|
||||
code == StatusOK ? data["url"] : false
|
||||
end
|
||||
|
||||
def upload opts = {}
|
||||
code, data = IO.put_file(opts[:url],
|
||||
opts[:file],
|
||||
opts[:bucket],
|
||||
opts[:key],
|
||||
opts[:mime_type],
|
||||
opts[:note],
|
||||
opts[:callback_params],
|
||||
opts[:enable_crc32_check])
|
||||
code == StatusOK
|
||||
end
|
||||
|
||||
def stat(bucket, key)
|
||||
code, data = RS.stat(bucket, key)
|
||||
code == StatusOK ? data : false
|
||||
end
|
||||
|
||||
def get(bucket, key, save_as = nil, expires_in = nil, version = nil)
|
||||
code, data = RS.get(bucket, key, save_as, expires_in, version)
|
||||
code == StatusOK ? data : false
|
||||
end
|
||||
|
||||
def download(bucket, key, save_as = nil, expires_in = nil, version = nil)
|
||||
code, data = RS.get(bucket, key, save_as, expires_in, version)
|
||||
code == StatusOK ? data["url"] : false
|
||||
end
|
||||
|
||||
def delete(bucket, key)
|
||||
code, data = RS.delete(bucket, key)
|
||||
code == StatusOK
|
||||
end
|
||||
|
||||
def batch(command, bucket, keys)
|
||||
code, data = RS.batch(command, bucket, keys)
|
||||
code == StatusOK ? data : false
|
||||
end
|
||||
|
||||
def batch_stat(bucket, keys)
|
||||
code, data = RS.batch_stat(bucket, keys)
|
||||
code == StatusOK ? data : false
|
||||
end
|
||||
|
||||
def batch_get(bucket, keys)
|
||||
code, data = RS.batch_get(bucket, keys)
|
||||
code == StatusOK ? data : false
|
||||
end
|
||||
|
||||
def batch_download(bucket, keys)
|
||||
code, data = RS.batch_get(bucket, keys)
|
||||
return false unless code == StatusOK
|
||||
links = []
|
||||
data.each { |e| links << e["data"]["url"] }
|
||||
links
|
||||
end
|
||||
|
||||
def batch_delete(bucket, keys)
|
||||
code, data = RS.batch_delete(bucket, keys)
|
||||
code == StatusOK ? data : false
|
||||
end
|
||||
|
||||
def publish(domain, bucket)
|
||||
code, data = RS.publish(domain, bucket)
|
||||
code == StatusOK
|
||||
end
|
||||
|
||||
def unpublish(domain)
|
||||
code, data = RS.unpublish(domain)
|
||||
code == StatusOK
|
||||
end
|
||||
|
||||
def drop(bucket)
|
||||
code, data = RS.drop(bucket)
|
||||
code == StatusOK
|
||||
end
|
||||
|
||||
def image_info(url)
|
||||
code, data = Image.info(url)
|
||||
code == StatusOK ? data : false
|
||||
end
|
||||
|
||||
def image_preview_url(url, spec)
|
||||
Image.preivew_url(url, spec)
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
@@ -1,83 +0,0 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'qiniu/rs/exceptions'
|
||||
|
||||
module Qiniu
|
||||
module RS
|
||||
module Auth
|
||||
class << self
|
||||
include Utils
|
||||
|
||||
def exchange_by_password!(username, password)
|
||||
@username = username
|
||||
@password = password
|
||||
post_data = {
|
||||
:client_id => Config.settings[:client_id],
|
||||
:grant_type => "password",
|
||||
:username => username,
|
||||
:password => password
|
||||
}
|
||||
code, data = http_request Config.settings[:auth_url], post_data
|
||||
reset_token(data["access_token"], data["refresh_token"]) if code == 200
|
||||
[code, data]
|
||||
end
|
||||
|
||||
def exchange_by_refresh_token!(refresh_token)
|
||||
post_data = {
|
||||
:client_id => Config.settings[:client_id],
|
||||
:grant_type => "refresh_token",
|
||||
:refresh_token => refresh_token
|
||||
}
|
||||
code, data = http_request Config.settings[:auth_url], post_data
|
||||
reset_token(data["access_token"], data["refresh_token"]) if code == 200
|
||||
[code, data]
|
||||
end
|
||||
|
||||
def reset_token(access_token, refresh_token)
|
||||
@access_token = access_token
|
||||
@refresh_token = refresh_token
|
||||
end
|
||||
|
||||
def call_with_logged_in(url, data, retry_times = 0)
|
||||
raise MissingAccessToken if @access_token.nil?
|
||||
code, data = http_request url, data, {:access_token => @access_token}
|
||||
if code == 401
|
||||
raise MissingRefreshToken if @refresh_token.nil?
|
||||
code, data = exchange_by_refresh_token!(@refresh_token)
|
||||
if code == 401
|
||||
raise MissingUsernameOrPassword if (@username.nil? || @password.nil?)
|
||||
code, data = exchange_by_password!(@username, @password)
|
||||
end
|
||||
if code == 200
|
||||
retry_times += 1
|
||||
if Config.settings[:auto_reconnect] && retry_times < Config.settings[:max_retry_times]
|
||||
return call_with_logged_in(url, data, retry_times)
|
||||
end
|
||||
end
|
||||
end
|
||||
[code, data]
|
||||
end
|
||||
|
||||
def call_with_signature(url, data, retry_times = 0)
|
||||
code, data = http_request url, data, {:signature_auth => true}
|
||||
[code, data]
|
||||
end
|
||||
|
||||
def request(url, data = nil)
|
||||
begin
|
||||
if Config.settings[:access_key].empty? || Config.settings[:secret_key].empty?
|
||||
code, data = Auth.call_with_logged_in(url, data)
|
||||
else
|
||||
code, data = Auth.call_with_signature(url, data)
|
||||
end
|
||||
rescue [MissingAccessToken, MissingRefreshToken, MissingUsernameOrPassword] => e
|
||||
Log.logger.error e
|
||||
code, data = 401, {}
|
||||
end
|
||||
[code, data]
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,20 +0,0 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
module Qiniu
|
||||
module RS
|
||||
module Image
|
||||
class << self
|
||||
include Utils
|
||||
|
||||
def info(url)
|
||||
Utils.http_request url + '/imageInfo', nil, {:method => :get}
|
||||
end
|
||||
|
||||
def preivew_url(url, spec)
|
||||
url + '/imagePreview/' + spec.to_s
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,42 +0,0 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'mime/types'
|
||||
require 'digest/sha1'
|
||||
require 'qiniu/rs/exceptions'
|
||||
|
||||
module Qiniu
|
||||
module RS
|
||||
module IO
|
||||
class << self
|
||||
include Utils
|
||||
|
||||
def put_auth(expires_in = nil, callback_url = nil)
|
||||
url = Config.settings[:io_host] + "/put-auth/"
|
||||
url += "#{expires_in}" if !expires_in.nil? && expires_in > 0
|
||||
if !callback_url.nil? && !callback_url.empty?
|
||||
encoded_callback_url = Utils.urlsafe_base64_encode(callback_url)
|
||||
url += "/callback/#{encoded_callback_url}"
|
||||
end
|
||||
Auth.request(url)
|
||||
end
|
||||
|
||||
def put_file(url, local_file, bucket = nil, key = nil, mime_type = nil, custom_meta = nil, callback_params = nil, enable_crc32_check = false)
|
||||
raise NoSuchFileError unless File.exist?(local_file)
|
||||
key = Digest::SHA1.hexdigest(local_file + Time.now.to_s) if key.nil?
|
||||
entry_uri = bucket + ':' + key
|
||||
if mime_type.nil?
|
||||
mime = MIME::Types.type_for local_file
|
||||
mime_type = mime.empty? ? 'application/octet-stream' : mime[0].content_type
|
||||
end
|
||||
action_params = '/rs-put/' + Utils.urlsafe_base64_encode(entry_uri) + '/mimeType/' + Utils.urlsafe_base64_encode(mime_type)
|
||||
action_params += '/meta/' + Utils.urlsafe_base64_encode(custom_meta) unless custom_meta.nil?
|
||||
action_params += '/crc32/' + Utils.crc32checksum(local_file).to_s if enable_crc32_check
|
||||
callback_params = {:bucket => bucket, :key => key, :mime_type => mime_type} if callback_params.nil?
|
||||
callback_query_string = Utils.generate_query_string(callback_params)
|
||||
Utils.upload_multipart_data(url, local_file, action_params, callback_query_string)
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,63 +0,0 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
module Qiniu
|
||||
module RS
|
||||
module RS
|
||||
class << self
|
||||
include Utils
|
||||
|
||||
def stat(bucket, key)
|
||||
Auth.request Config.settings[:rs_host] + '/stat/' + encode_entry_uri(bucket, key)
|
||||
end
|
||||
|
||||
def get(bucket, key, save_as = nil, expires_in = nil, version = nil)
|
||||
url = Config.settings[:rs_host] + '/get/' + encode_entry_uri(bucket, key)
|
||||
url += '/base/' + version unless version.nil?
|
||||
url += '/attName/' + Utils.urlsafe_base64_encode(save_as) unless save_as.nil?
|
||||
url += '/expires/' + expires_in.to_s if !expires_in.nil? && expires_in > 0
|
||||
Auth.request url
|
||||
end
|
||||
|
||||
def delete(bucket, key)
|
||||
Auth.request Config.settings[:rs_host] + '/delete/' + encode_entry_uri(bucket, key)
|
||||
end
|
||||
|
||||
def publish(domain, bucket)
|
||||
encoded_domain = Utils.urlsafe_base64_encode(domain)
|
||||
Auth.request Config.settings[:rs_host] + "/publish/#{encoded_domain}/from/#{bucket}"
|
||||
end
|
||||
|
||||
def unpublish(domain)
|
||||
encoded_domain = Utils.urlsafe_base64_encode(domain)
|
||||
Auth.request Config.settings[:rs_host] + "/unpublish/#{encoded_domain}"
|
||||
end
|
||||
|
||||
def drop(bucket)
|
||||
Auth.request Config.settings[:rs_host] + "/drop/#{bucket}"
|
||||
end
|
||||
|
||||
def batch(command, bucket, keys)
|
||||
execs = []
|
||||
keys.each do |key|
|
||||
encoded_uri = encode_entry_uri(bucket, key)
|
||||
execs << "op=/#{command}/#{encoded_uri}"
|
||||
end
|
||||
Auth.request Config.settings[:rs_host] + "/batch?" + execs.join("&")
|
||||
end
|
||||
|
||||
def batch_get(bucket, keys)
|
||||
batch("get", bucket, keys)
|
||||
end
|
||||
|
||||
def batch_stat(bucket, keys)
|
||||
batch("stat", bucket, keys)
|
||||
end
|
||||
|
||||
def batch_delete(bucket, keys)
|
||||
batch("delete", bucket, keys)
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,151 +0,0 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'uri'
|
||||
require 'json'
|
||||
require 'zlib'
|
||||
require 'base64'
|
||||
require 'rest_client'
|
||||
require 'hmac-sha1'
|
||||
require 'qiniu/rs/exceptions'
|
||||
|
||||
module Qiniu
|
||||
module RS
|
||||
module Utils extend self
|
||||
|
||||
def urlsafe_base64_encode content
|
||||
Base64.encode64(content).strip.gsub('+', '-').gsub('/','_').gsub(/\r?\n/, '')
|
||||
end
|
||||
|
||||
def urlsafe_base64_decode encoded_content
|
||||
Base64.decode64 encoded_content.gsub('_','/').gsub('-', '+')
|
||||
end
|
||||
|
||||
def encode_entry_uri(bucket, key)
|
||||
entry_uri = bucket + ':' + key
|
||||
urlsafe_base64_encode(entry_uri)
|
||||
end
|
||||
|
||||
def safe_json_parse(data)
|
||||
JSON.parse(data)
|
||||
rescue JSON::ParserError
|
||||
{}
|
||||
end
|
||||
|
||||
def send_request_with url, data = nil, options = {}
|
||||
options[:method] = Config.settings[:method] unless options[:method]
|
||||
options[:content_type] = Config.settings[:content_type] unless options[:content_type]
|
||||
header_options = {
|
||||
:accept => :json,
|
||||
:user_agent => Config.settings[:user_agent]
|
||||
}
|
||||
if options[:signature_auth] && options[:signature_auth] == true
|
||||
signature_token = generate_qbox_signature(Config.settings[:access_key], Config.settings[:secret_key], url, data)
|
||||
header_options.merge!('Authorization' => "QBox #{signature_token}")
|
||||
elsif options[:access_token]
|
||||
header_options.merge!('Authorization' => "Bearer #{options[:access_token]}")
|
||||
end
|
||||
case options[:method]
|
||||
when :get
|
||||
response = RestClient.get url, header_options
|
||||
when :post
|
||||
header_options.merge!(:content_type => options[:content_type])
|
||||
response = RestClient.post url, data, header_options
|
||||
end
|
||||
code = response.respond_to?(:code) ? response.code.to_i : 0
|
||||
if code != 200
|
||||
raise RequestFailed.new(response)
|
||||
else
|
||||
data = {}
|
||||
body = response.respond_to?(:body) ? response.body : {}
|
||||
data = safe_json_parse(body) unless body.empty?
|
||||
end
|
||||
[code, data]
|
||||
end
|
||||
|
||||
def http_request url, data = nil, options = {}
|
||||
retry_times = 0
|
||||
begin
|
||||
retry_times += 1
|
||||
send_request_with url, data, options
|
||||
rescue Errno::ECONNRESET => err
|
||||
if Config.settings[:auto_reconnect] && retry_times < Config.settings[:max_retry_times]
|
||||
retry
|
||||
else
|
||||
Log.logger.error err
|
||||
end
|
||||
rescue => e
|
||||
Log.logger.warn "#{e.message} => Utils.http_request('#{url}')"
|
||||
code = 0
|
||||
data = {}
|
||||
body = {}
|
||||
if e.respond_to? :response
|
||||
res = e.response
|
||||
code = res.code.to_i if res.respond_to? :code
|
||||
body = res.respond_to?(:body) ? res.body : ""
|
||||
data = safe_json_parse(body) unless body.empty?
|
||||
end
|
||||
[code, data]
|
||||
end
|
||||
end
|
||||
|
||||
def upload_multipart_data(url, filepath, action_string, callback_query_string = '')
|
||||
code, data = 0, {}
|
||||
begin
|
||||
header_options = {
|
||||
:accept => :json,
|
||||
:user_agent => Config.settings[:user_agent]
|
||||
}
|
||||
post_data = {
|
||||
:file => File.new(filepath, 'rb'),
|
||||
:params => callback_query_string,
|
||||
:action => action_string,
|
||||
:multipart => true
|
||||
}
|
||||
response = RestClient.post url, post_data, header_options
|
||||
body = response.respond_to?(:body) ? response.body : ""
|
||||
data = safe_json_parse(body) unless body.empty?
|
||||
code = response.code.to_i if response.respond_to?(:code)
|
||||
rescue Errno::ECONNRESET => err
|
||||
Log.logger.error err
|
||||
rescue => e
|
||||
Log.logger.warn "#{e.message} => Utils.http_request('#{url}')"
|
||||
res = e.response
|
||||
if e.respond_to? :response
|
||||
res = e.response
|
||||
code = res.code.to_i if res.respond_to? :code
|
||||
body = res.respond_to?(:body) ? res.body : ""
|
||||
data = safe_json_parse(body) unless body.empty?
|
||||
end
|
||||
end
|
||||
[code, data]
|
||||
end
|
||||
|
||||
def generate_query_string(params)
|
||||
return params if params.is_a?(String)
|
||||
total_param = params.map { |key, value| key.to_s+"="+value.to_s }
|
||||
URI.escape(total_param.join("&"))
|
||||
end
|
||||
|
||||
def crc32checksum(filepath)
|
||||
File.open(filepath, "rb") { |f| Zlib.crc32 f.read }
|
||||
end
|
||||
|
||||
def generate_qbox_signature(access_key, secret_key, url, params)
|
||||
uri = URI.parse(url)
|
||||
signature = uri.path
|
||||
query_string = uri.query
|
||||
signature += '?' + query_string if !query_string.nil? && !query_string.empty?
|
||||
signature += "\n";
|
||||
if params.is_a?(Hash)
|
||||
total_param = params.map { |key, value| key.to_s+"="+value.to_s }
|
||||
signature += total_param.join("&")
|
||||
end
|
||||
hmac = HMAC::SHA1.new(secret_key)
|
||||
hmac.update(signature)
|
||||
encoded_digest = urlsafe_base64_encode(hmac.digest)
|
||||
%Q(#{access_key}:#{encoded_digest})
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,7 +0,0 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
module Qiniu
|
||||
module RS
|
||||
VERSION = "2.0.2"
|
||||
end
|
||||
end
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'qiniu/upload'
|
||||
require 'qiniu/resumable_upload'
|
||||
require 'qiniu/management'
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'hmac-sha1'
|
||||
require 'qiniu/config'
|
||||
require 'qiniu/utils'
|
||||
|
||||
### AccessToken 类已经过时,请改用 Qiniu::Auth.generate_acctoken 方法 ###
|
||||
|
||||
module Qiniu
|
||||
class AccessToken
|
||||
|
||||
include Utils
|
||||
|
||||
attr_accessor :access_key, :secret_key
|
||||
|
||||
def generate_encoded_digest(signature)
|
||||
hmac = HMAC::SHA1.new(@secret_key)
|
||||
hmac.update(signature)
|
||||
urlsafe_base64_encode(hmac.digest)
|
||||
end
|
||||
|
||||
end # AccessToken
|
||||
end # module Qiniu
|
||||
Executable
+34
@@ -0,0 +1,34 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'json'
|
||||
require 'qiniu/tokens/access_token'
|
||||
require 'qiniu/utils'
|
||||
|
||||
### DownloadToken 类已经过时,请改用 Qiniu::Auth.authorize_download_url 方法 ###
|
||||
### 或 Qiniu::Auth.authorize_download_url_2 方法 ###
|
||||
|
||||
module Qiniu
|
||||
class DownloadToken < AccessToken
|
||||
|
||||
include Utils
|
||||
|
||||
attr_accessor :pattern, :expires_in
|
||||
|
||||
def initialize(opts = {})
|
||||
@pattern = opts[:pattern]
|
||||
@expires_in = opts[:expires_in] || 3600
|
||||
end
|
||||
|
||||
def generate_signature
|
||||
params = {"S" => @pattern, "E" => Time.now.to_i + @expires_in}
|
||||
Utils.urlsafe_base64_encode(params.to_json)
|
||||
end
|
||||
|
||||
def generate_token
|
||||
signature = generate_signature
|
||||
encoded_digest = generate_encoded_digest(signature)
|
||||
%Q(#{@access_key}:#{encoded_digest}:#{signature})
|
||||
end
|
||||
|
||||
end # moidule DownloadToken
|
||||
end # module Qiniu
|
||||
Executable
+38
@@ -0,0 +1,38 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'cgi'
|
||||
require 'json'
|
||||
require 'qiniu/tokens/access_token'
|
||||
|
||||
module Qiniu
|
||||
class QboxToken < AccessToken
|
||||
|
||||
include Utils
|
||||
|
||||
attr_accessor :url, :params
|
||||
|
||||
def initialize(opts = {})
|
||||
@url = opts[:url]
|
||||
@params = opts[:params]
|
||||
end
|
||||
|
||||
def generate_signature
|
||||
uri = URI.parse(@url)
|
||||
signature = uri.path
|
||||
query_string = uri.query
|
||||
signature += '?' + query_string if !query_string.nil? && !query_string.empty?
|
||||
signature += "\n"
|
||||
if @params.is_a?(Hash)
|
||||
params_string = HTTP.generate_query_string(@params)
|
||||
signature += params_string
|
||||
end
|
||||
signature
|
||||
end
|
||||
|
||||
def generate_token
|
||||
encoded_digest = generate_encoded_digest(generate_signature)
|
||||
%Q(#{@access_key}:#{encoded_digest})
|
||||
end
|
||||
|
||||
end # module QboxToken
|
||||
end # module Qiniu
|
||||
Executable
+55
@@ -0,0 +1,55 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'json'
|
||||
require 'qiniu/tokens/access_token'
|
||||
require 'qiniu/utils'
|
||||
|
||||
### UploadToken 类已经过时,请改用 Qiniu::Auth.generate_uptoken 方法 ###
|
||||
|
||||
module Qiniu
|
||||
class UploadToken < AccessToken
|
||||
|
||||
include Utils
|
||||
|
||||
attr_accessor :scope, :expires_in, :callback_url, :callback_body, :callback_body_type, :customer, :escape, :async_options, :return_body, :return_url
|
||||
|
||||
def initialize(opts = {})
|
||||
@scope = opts[:scope]
|
||||
@expires_in = opts[:expires_in] || 3600
|
||||
@callback_url = opts[:callback_url]
|
||||
@callback_body = opts[:callback_body]
|
||||
@callback_body_type = opts[:callback_body_type]
|
||||
@customer = opts[:customer]
|
||||
@escape = opts[:escape]
|
||||
@persistent_ops = opts[:persistent_ops]
|
||||
@persistent_notify_url = opts[:persistent_notify_url]
|
||||
@persistent_pipeline = opts[:persistent_pipeline]
|
||||
@return_body = opts[:return_body]
|
||||
@return_url = opts[:return_url]
|
||||
end
|
||||
|
||||
def generate_signature
|
||||
params = {:scope => @scope, :deadline => Time.now.to_i + @expires_in}
|
||||
params[:callbackUrl] = @callback_url if !@callback_url.nil? && !@callback_url.empty?
|
||||
params[:callbackBody] = @callback_body if !@callback_body.nil? && !@callback_body.empty?
|
||||
params[:callbackBodyType] = @callback_body_type if !@callback_body_type.nil? && !@callback_body_type.empty?
|
||||
params[:customer] = @customer if !@customer.nil? && !@customer.empty?
|
||||
params[:escape] = 1 if @escape == 1 || @escape == true
|
||||
params[:returnBody] = @return_body if !@return_body.nil? && !@return_body.empty?
|
||||
params[:returnUrl] = @return_url if !@return_url.nil? && !@return_url.empty?
|
||||
|
||||
params[:persistentOps] = @persistent_ops if !@persistent_ops.nil? && !@persistent_ops.empty?
|
||||
params[:persistentNotifyUrl] = @persistent_notify_url if !@persistent_notify_url.nil? && !@persistent_notify_url.empty?
|
||||
params[:persistentPipeline] = @persistent_pipeline if !@persistent_pipeline.nil? && !@persistent_pipeline.empty?
|
||||
|
||||
Utils.urlsafe_base64_encode(params.to_json)
|
||||
end
|
||||
|
||||
def generate_token
|
||||
signature = generate_signature
|
||||
encoded_digest = generate_encoded_digest(signature)
|
||||
%Q(#{@access_key}:#{encoded_digest}:#{signature})
|
||||
end
|
||||
|
||||
end # module UploadToken
|
||||
end # module Qiniu
|
||||
@@ -0,0 +1,143 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
# vim: sw=2 ts=2
|
||||
|
||||
module Qiniu
|
||||
module Storage
|
||||
class << self
|
||||
include Utils
|
||||
|
||||
def upload_with_token(uptoken,
|
||||
local_file,
|
||||
bucket,
|
||||
key = nil,
|
||||
mime_type = nil,
|
||||
custom_meta = nil,
|
||||
callback_params = nil,
|
||||
enable_crc32_check = false,
|
||||
rotate = nil)
|
||||
action_params = _generate_action_params(
|
||||
local_file,
|
||||
bucket,
|
||||
key,
|
||||
mime_type,
|
||||
custom_meta,
|
||||
enable_crc32_check,
|
||||
rotate
|
||||
)
|
||||
|
||||
if callback_params.nil?
|
||||
callback_params = {:bucket => bucket, :key => key, :mime_type => mime_type}
|
||||
end
|
||||
callback_query_string = HTTP.generate_query_string(callback_params)
|
||||
|
||||
url = Config.settings[:up_host] + '/upload'
|
||||
post_data = {
|
||||
:params => callback_query_string,
|
||||
:action => action_params,
|
||||
:file => File.new(local_file, 'rb'),
|
||||
:multipart => true
|
||||
}
|
||||
if !uptoken.nil? then
|
||||
post_data[:auth] = uptoken unless uptoken.nil?
|
||||
end
|
||||
|
||||
return HTTP.api_post(url, post_data)
|
||||
end # upload_with_token
|
||||
|
||||
def upload_with_token_2(uptoken,
|
||||
local_file,
|
||||
key = nil,
|
||||
x_vars = nil,
|
||||
opts = {})
|
||||
|
||||
file = File.new(local_file, 'rb')
|
||||
return upload_with_token_2_file_stream(uptoken, file, key, x_vars, opts)
|
||||
end # upload_with_token_2
|
||||
|
||||
def upload_with_token_2_file_stream(uptoken,
|
||||
file,
|
||||
key = nil,
|
||||
x_vars = nil,
|
||||
opts = {})
|
||||
### 构造URL
|
||||
url = Config.settings[:up_host]
|
||||
url[/\/*$/] = ''
|
||||
url += '/'
|
||||
|
||||
### 构造HTTP Body
|
||||
if not opts[:content_type].nil?
|
||||
file.define_singleton_method("content_type") do
|
||||
opts[:content_type]
|
||||
end
|
||||
end
|
||||
|
||||
post_data = {
|
||||
:file => file,
|
||||
:multipart => true,
|
||||
}
|
||||
if not uptoken.nil?
|
||||
post_data[:token] = uptoken
|
||||
end
|
||||
if not key.nil?
|
||||
post_data[:key] = key
|
||||
end
|
||||
if x_vars.is_a?(Hash)
|
||||
post_data.merge!(x_vars)
|
||||
end
|
||||
|
||||
### 发送请求
|
||||
HTTP.api_post(url, post_data)
|
||||
end
|
||||
|
||||
### 授权举例
|
||||
# put_policy.bucket | put_policy.key | key | 语义 | 授权
|
||||
# :---------------- | :------------- | :------ | :--- | :---
|
||||
# trivial_bucket | <nil> | <nil> | 新增 | 允许,最终key为1)使用put_policy.save_key生成的值或2)资源内容的Hash值
|
||||
# trivial_bucket | <nil> | foo.txt | 新增 | 允许
|
||||
# trivial_bucket | <nil> | bar.jpg | 新增 | 允许
|
||||
# trivial_bucket | foo.txt | <nil> | 覆盖 | 允许,由SDK将put_policy.key赋值给key实现
|
||||
# trivial_bucket | foo.txt | foo.txt | 覆盖 | 允许
|
||||
# trivial_bucket | foo.txt | bar.jpg | 覆盖 | 禁止,put_policy.key与key不一致
|
||||
def upload_with_put_policy(put_policy,
|
||||
local_file,
|
||||
key = nil,
|
||||
x_vars = nil,
|
||||
opts = {})
|
||||
uptoken = Auth.generate_uptoken(put_policy)
|
||||
if key.nil? then
|
||||
key = put_policy.key
|
||||
end
|
||||
|
||||
return upload_with_token_2(uptoken, local_file, key, x_vars, opts)
|
||||
end # upload_with_put_policy
|
||||
|
||||
private
|
||||
def _generate_action_params(local_file,
|
||||
bucket,
|
||||
key = nil,
|
||||
mime_type = nil,
|
||||
custom_meta = nil,
|
||||
enable_crc32_check = false,
|
||||
rotate = nil)
|
||||
raise NoSuchFileError, local_file unless File.exist?(local_file)
|
||||
|
||||
if key.nil?
|
||||
key = Digest::SHA1.hexdigest(local_file + Time.now.to_s)
|
||||
end
|
||||
|
||||
entry_uri = bucket + ':' + key
|
||||
if mime_type.nil? || mime_type.empty?
|
||||
mime = MIME::Types.type_for local_file
|
||||
mime_type = mime.empty? ? 'application/octet-stream' : mime[0].content_type
|
||||
end
|
||||
|
||||
action_params = '/rs-put/' + Utils.urlsafe_base64_encode(entry_uri) + '/mimeType/' + Utils.urlsafe_base64_encode(mime_type)
|
||||
action_params += '/meta/' + Utils.urlsafe_base64_encode(custom_meta) unless custom_meta.nil?
|
||||
action_params += '/crc32/' + Utils.crc32checksum(local_file).to_s if enable_crc32_check
|
||||
action_params += '/rotate/' + rotate if !rotate.nil? && rotate.to_i >= 0
|
||||
action_params
|
||||
end # _generate_action_params
|
||||
|
||||
end # class << self
|
||||
end # module Storage
|
||||
end # module Qiniu
|
||||
Executable
+109
@@ -0,0 +1,109 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'uri'
|
||||
require 'cgi'
|
||||
require 'json'
|
||||
require 'zlib'
|
||||
require 'base64'
|
||||
require 'rest_client'
|
||||
require 'hmac-sha1'
|
||||
require 'qiniu/exceptions'
|
||||
|
||||
module Qiniu
|
||||
module Utils extend self
|
||||
|
||||
def urlsafe_base64_encode content
|
||||
Base64.encode64(content).strip.gsub('+', '-').gsub('/','_').gsub(/\r?\n/, '')
|
||||
end
|
||||
|
||||
def urlsafe_base64_decode encoded_content
|
||||
Base64.decode64 encoded_content.gsub('_','/').gsub('-', '+')
|
||||
end
|
||||
|
||||
def encode_entry_uri(bucket, key)
|
||||
entry_uri = bucket + ':' + key
|
||||
urlsafe_base64_encode(entry_uri)
|
||||
end
|
||||
|
||||
def safe_json_parse(data)
|
||||
JSON.parse(data)
|
||||
rescue JSON::ParserError
|
||||
{}
|
||||
end
|
||||
|
||||
def debug(msg)
|
||||
if Config.settings[:enable_debug]
|
||||
Log.logger.debug(msg)
|
||||
end
|
||||
end
|
||||
|
||||
### 已过时,仅作为兼容接口保留
|
||||
def send_request_with url, data = nil, options = {}
|
||||
options[:method] = Config.settings[:method] unless options[:method]
|
||||
options[:content_type] = Config.settings[:content_type] unless options[:content_type]
|
||||
header_options = {
|
||||
:accept => :json,
|
||||
:user_agent => Config.settings[:user_agent]
|
||||
}
|
||||
auth_token = nil
|
||||
if !options[:qbox_signature_token].nil? && !options[:qbox_signature_token].empty?
|
||||
auth_token = 'QBox ' + options[:qbox_signature_token]
|
||||
elsif !options[:upload_signature_token].nil? && !options[:upload_signature_token].empty?
|
||||
auth_token = 'UpToken ' + options[:upload_signature_token]
|
||||
elsif options[:access_token]
|
||||
auth_token = 'Bearer ' + options[:access_token]
|
||||
end
|
||||
header_options.merge!('Authorization' => auth_token) unless auth_token.nil?
|
||||
case options[:method]
|
||||
when :get
|
||||
response = RestClient.get(url, header_options)
|
||||
when :post
|
||||
header_options.merge!(:content_type => options[:content_type])
|
||||
response = RestClient.post(url, data, header_options)
|
||||
end
|
||||
code = response.respond_to?(:code) ? response.code.to_i : 0
|
||||
unless HTTP.is_response_ok?(code)
|
||||
raise RequestFailed.new("Request Failed", response)
|
||||
else
|
||||
data = {}
|
||||
body = response.respond_to?(:body) ? response.body : {}
|
||||
raw_headers = response.respond_to?(:raw_headers) ? response.raw_headers : {}
|
||||
data = safe_json_parse(body) unless body.empty?
|
||||
end
|
||||
[code, data, raw_headers]
|
||||
end # send_request_with
|
||||
|
||||
### 已过时,仅作为兼容接口保留
|
||||
def http_request url, data = nil, options = {}
|
||||
retry_times = 0
|
||||
begin
|
||||
retry_times += 1
|
||||
send_request_with url, data, options
|
||||
rescue Errno::ECONNRESET => err
|
||||
if Config.settings[:auto_reconnect] && retry_times < Config.settings[:max_retry_times]
|
||||
retry
|
||||
else
|
||||
Log.logger.error err
|
||||
end
|
||||
rescue => e
|
||||
Log.logger.warn "#{e.message} => Utils.http_request('#{url}')"
|
||||
code = 0
|
||||
data = {}
|
||||
body = {}
|
||||
if e.respond_to? :response
|
||||
res = e.response
|
||||
code = res.code.to_i if res.respond_to? :code
|
||||
body = res.respond_to?(:body) ? res.body : ""
|
||||
raw_headers = res.respond_to?(:raw_headers) ? res.raw_headers : {}
|
||||
data = safe_json_parse(body) unless body.empty?
|
||||
end
|
||||
[code, data, raw_headers]
|
||||
end
|
||||
end
|
||||
|
||||
def crc32checksum(filepath)
|
||||
File.open(filepath, "rb") { |f| Zlib.crc32 f.read }
|
||||
end
|
||||
|
||||
end # module Utils
|
||||
end # module Qiniu
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
module Qiniu
|
||||
module Version
|
||||
MAJOR = 6
|
||||
MINOR = 5
|
||||
PATCH = 1
|
||||
# Returns a version string by joining <tt>MAJOR</tt>, <tt>MINOR</tt>, and <tt>PATCH</tt> with <tt>'.'</tt>
|
||||
#
|
||||
# Example
|
||||
#
|
||||
# Version.to_s # '1.0.2'
|
||||
def self.to_s
|
||||
[MAJOR, MINOR, PATCH].join('.')
|
||||
end
|
||||
end # Version
|
||||
end # module Qiniu
|
||||
@@ -1,28 +0,0 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require File.expand_path('../lib/qiniu/rs/version', __FILE__)
|
||||
|
||||
Gem::Specification.new do |gem|
|
||||
gem.authors = ["why404"]
|
||||
gem.email = ["why404@gmail.com"]
|
||||
gem.description = %q{Qiniu Resource (Cloud) Storage SDK for Ruby. See: http://docs.qiniutek.com/v2/sdk/ruby/}
|
||||
gem.summary = %q{Qiniu Resource (Cloud) Storage SDK for Ruby}
|
||||
gem.homepage = "https://github.com/why404/qiniu-rs"
|
||||
|
||||
gem.files = `git ls-files`.split($\)
|
||||
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
|
||||
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
|
||||
gem.name = "qiniu-rs"
|
||||
gem.require_paths = ["lib"]
|
||||
gem.version = Qiniu::RS::VERSION
|
||||
|
||||
# specify any dependencies here; for example:
|
||||
gem.add_development_dependency "rake", "~> 0.9.2.2"
|
||||
gem.add_development_dependency "rspec", "~> 2.10.0"
|
||||
gem.add_development_dependency "fakeweb", "~> 1.3.0"
|
||||
gem.add_runtime_dependency "json", "~> 1.7.3"
|
||||
gem.add_runtime_dependency "rest-client", "~> 1.6.7"
|
||||
gem.add_runtime_dependency "mime-types", "~> 1.19"
|
||||
gem.add_runtime_dependency "ruby-hmac", "~> 0.4.0"
|
||||
gem.add_runtime_dependency "jruby-openssl", "~> 0.7.7" if RUBY_PLATFORM == "java"
|
||||
end
|
||||
Executable
+29
@@ -0,0 +1,29 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require File.expand_path('../lib/qiniu/version', __FILE__)
|
||||
|
||||
Gem::Specification.new do |gem|
|
||||
gem.authors = ["why404","BluntBlade"]
|
||||
gem.email = ["sdk@qiniu.com"]
|
||||
gem.description = %q{Qiniu Resource (Cloud) Storage SDK for Ruby. See: http://developer.qiniu.com/docs/v6/sdk/ruby-sdk.html}
|
||||
gem.summary = %q{Qiniu Resource (Cloud) Storage SDK for Ruby}
|
||||
gem.homepage = "https://github.com/qiniu/ruby-sdk"
|
||||
|
||||
gem.files = `git ls-files`.split($\)
|
||||
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
|
||||
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
|
||||
gem.name = "qiniu"
|
||||
gem.require_paths = ["lib"]
|
||||
gem.version = Qiniu::Version.to_s
|
||||
gem.license = "MIT"
|
||||
|
||||
# specify any dependencies here; for example:
|
||||
gem.add_development_dependency "rake", ">= 0.9"
|
||||
gem.add_development_dependency "rspec", ">= 2.11"
|
||||
gem.add_development_dependency "fakeweb", "~> 1.3"
|
||||
gem.add_runtime_dependency "json", "~> 1.8"
|
||||
gem.add_runtime_dependency "rest-client", "~> 1.7.3"
|
||||
gem.add_runtime_dependency "mime-types", "~> 2.4.3"
|
||||
gem.add_runtime_dependency "ruby-hmac", "~> 0.4"
|
||||
gem.add_runtime_dependency "jruby-openssl", "~> 0.7" if RUBY_PLATFORM == "java"
|
||||
end
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
source 'https://rubygems.org'
|
||||
|
||||
# Specify your gem's dependencies in rails3/qiniu.gemspec
|
||||
gemspec :name => 'qiniu'
|
||||
Executable
+29
@@ -0,0 +1,29 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require File.expand_path('../../lib/qiniu/version', __FILE__)
|
||||
|
||||
Gem::Specification.new do |gem|
|
||||
gem.authors = ["why404","BluntBlade"]
|
||||
gem.email = ["sdk@qiniu.com"]
|
||||
gem.description = %q{Qiniu Resource (Cloud) Storage SDK for Ruby. See: http://developer.qiniu.com/docs/v6/sdk/ruby-sdk.html}
|
||||
gem.summary = %q{Qiniu Resource (Cloud) Storage SDK for Ruby}
|
||||
gem.homepage = "https://github.com/qiniu/ruby-sdk"
|
||||
|
||||
gem.files = `git ls-files`.split($\)
|
||||
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
|
||||
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
|
||||
gem.name = "qiniu"
|
||||
gem.require_paths = ["lib"]
|
||||
gem.version = Qiniu::Version.to_s
|
||||
gem.license = "MIT"
|
||||
|
||||
# specify any dependencies here; for example:
|
||||
gem.add_development_dependency "rake", ">= 0.9"
|
||||
gem.add_development_dependency "rspec", ">= 2.11"
|
||||
gem.add_development_dependency "fakeweb", "~> 1.3"
|
||||
gem.add_runtime_dependency "json", "~> 1.8"
|
||||
gem.add_runtime_dependency "rest-client", "~> 1.7.3"
|
||||
gem.add_runtime_dependency "mime-types", "~> 1.19"
|
||||
gem.add_runtime_dependency "ruby-hmac", "~> 0.4"
|
||||
gem.add_runtime_dependency "jruby-openssl", "~> 0.7" if RUBY_PLATFORM == "java"
|
||||
end
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'spec_helper'
|
||||
require 'qiniu/abstract'
|
||||
|
||||
describe Qiniu::Abstract do
|
||||
before(:each) do
|
||||
@klass = Class.new do
|
||||
include Qiniu::Abstract
|
||||
|
||||
abstract_methods :foo, :bar
|
||||
end
|
||||
end
|
||||
|
||||
it "raises NotImplementedError" do
|
||||
proc {
|
||||
@klass.new.foo
|
||||
}.should raise_error(NotImplementedError)
|
||||
end
|
||||
|
||||
it "can be overridden" do
|
||||
subclass = Class.new(@klass) do
|
||||
def foo
|
||||
:overridden
|
||||
end
|
||||
end
|
||||
|
||||
subclass.new.foo.should == :overridden
|
||||
end
|
||||
end
|
||||
Executable
+128
@@ -0,0 +1,128 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
# vim: sw=2 ts=2
|
||||
|
||||
require 'spec_helper'
|
||||
require 'qiniu/auth'
|
||||
require 'qiniu/config'
|
||||
require 'qiniu/storage'
|
||||
require 'digest/sha1'
|
||||
|
||||
module Qiniu
|
||||
module Auth
|
||||
describe Auth do
|
||||
|
||||
before :all do
|
||||
@bucket = 'rubysdk'
|
||||
end
|
||||
after :all do
|
||||
end
|
||||
|
||||
### 测试私有资源下载
|
||||
context ".download_private_file" do
|
||||
it "should works" do
|
||||
### 生成Key
|
||||
key = 'a_private_file'
|
||||
key = make_unique_key_in_bucket(key)
|
||||
puts "key=#{key}"
|
||||
|
||||
### 上传测试文件
|
||||
pp = Auth::PutPolicy.new(@bucket, key)
|
||||
code, data, raw_headers = Qiniu::Storage.upload_with_put_policy(
|
||||
pp,
|
||||
__FILE__
|
||||
)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
puts raw_headers.inspect
|
||||
|
||||
### 获取下载地址
|
||||
code, data = Qiniu::Storage.get(@bucket, key)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
|
||||
url = data['url']
|
||||
|
||||
### 授权下载地址(不带参数)
|
||||
download_url = Qiniu::Auth.authorize_download_url(url)
|
||||
puts "download_url=#{download_url}"
|
||||
|
||||
result = RestClient.get(download_url)
|
||||
result.code.should == 200
|
||||
result.body.should_not be_empty
|
||||
|
||||
### 授权下载地址(带参数)
|
||||
download_url = Qiniu::Auth.authorize_download_url(
|
||||
url,
|
||||
{
|
||||
:fop => 'download/a.m3u8'
|
||||
}
|
||||
)
|
||||
puts "download_url=#{download_url}"
|
||||
|
||||
result = RestClient.get(download_url)
|
||||
result.code.should == 200
|
||||
result.body.should_not be_empty
|
||||
|
||||
### 删除文件
|
||||
code, data = Qiniu::Storage.delete(@bucket, key)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
### 测试回调签名
|
||||
context ".authenticate_callback_request" do
|
||||
it "should works" do
|
||||
url = '/test.php'
|
||||
body = 'name=xxx&size=1234'
|
||||
false.should == Qiniu::Auth.authenticate_callback_request('ABCD', url, body)
|
||||
false.should == Qiniu::Auth.authenticate_callback_request(Config.settings[:access_key], url, body)
|
||||
false.should == Qiniu::Auth.authenticate_callback_request('QBox ' + Config.settings[:access_key] + ':', url, body)
|
||||
false.should == Qiniu::Auth.authenticate_callback_request('QBox ' + Config.settings[:access_key] + ':????', url, body)
|
||||
|
||||
acctoken = Qiniu::Auth.generate_acctoken(url, body)
|
||||
auth_str = 'QBox ' + acctoken
|
||||
|
||||
false.should == Qiniu::Auth.authenticate_callback_request(auth_str + ' ', url, body)
|
||||
true.should == Qiniu::Auth.authenticate_callback_request(auth_str, url, body)
|
||||
true.should == Qiniu::Auth.authenticate_callback_request(acctoken, url, body)
|
||||
end
|
||||
end
|
||||
end # module Auth
|
||||
|
||||
module Exception_Auth
|
||||
describe Exception_Auth, :not_set_ak_sk => true do
|
||||
### 测试未设置 ak/sk 的异常抛出情况
|
||||
context ".not_set_ak_sk" do
|
||||
it "should works" do
|
||||
puts Qiniu::Config.instance_variable_get("@settings").inspect
|
||||
|
||||
begin
|
||||
uptoken = Qiniu::Auth.generate_uptoken({})
|
||||
rescue => e
|
||||
e.message.should == "Please set Qiniu's access_key and secret_key before authorize any tokens."
|
||||
else
|
||||
fail "Not raise any exception."
|
||||
end
|
||||
|
||||
begin
|
||||
download_url = Qiniu::Auth.authorize_download_url("http://test.qiniudn.com/a_private_file")
|
||||
rescue => e
|
||||
e.message.should == "Please set Qiniu's access_key and secret_key before authorize any tokens."
|
||||
else
|
||||
fail "Not raise any exception."
|
||||
end
|
||||
|
||||
begin
|
||||
acctoken = Qiniu::Auth.generate_acctoken("http://rsf.qbox.me/list")
|
||||
rescue => e
|
||||
e.message.should == "Please set Qiniu's access_key and secret_key before authorize any tokens."
|
||||
else
|
||||
fail "Not raise any exception."
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end # module Exception_Auth
|
||||
end # module Qiniu
|
||||
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 13 KiB |
Executable
+84
@@ -0,0 +1,84 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'spec_helper'
|
||||
require 'qiniu/auth'
|
||||
require 'qiniu'
|
||||
require 'qiniu/fop'
|
||||
|
||||
module Qiniu
|
||||
module Fop
|
||||
describe Fop do
|
||||
|
||||
before :all do
|
||||
@bucket = 'rubysdk'
|
||||
pic_fname = "image_logo_for_test.png"
|
||||
@key = make_unique_key_in_bucket(pic_fname)
|
||||
|
||||
local_file = File.expand_path('../' + pic_fname, __FILE__)
|
||||
|
||||
upopts = {
|
||||
:scope => @bucket,
|
||||
:expires_in => 3600,
|
||||
:customer => "why404@gmail.com",
|
||||
:async_options => "imageView/1/w/120/h/120",
|
||||
:return_body => '{"size":$(fsize), "hash":$(etag), "width":$(imageInfo.width), "height":$(imageInfo.height)}'
|
||||
}
|
||||
uptoken = Qiniu.generate_upload_token(upopts)
|
||||
data = Qiniu.upload_file :uptoken => uptoken, :file => local_file, :bucket => @bucket, :key => @key
|
||||
puts data.inspect
|
||||
|
||||
data["size"].should_not be_zero
|
||||
data["hash"].should_not be_empty
|
||||
data["width"].should_not be_zero
|
||||
data["height"].should_not be_zero
|
||||
|
||||
result = Qiniu.get(@bucket, @key)
|
||||
result["url"].should_not be_empty
|
||||
puts result.inspect
|
||||
@source_image_url = result["url"]
|
||||
|
||||
@mogrify_options = {
|
||||
:thumbnail => "!120x120>",
|
||||
:gravity => "center",
|
||||
:crop => "!120x120a0a0",
|
||||
:quality => 85,
|
||||
:rotate => 45,
|
||||
:format => "jpg",
|
||||
:auto_orient => true
|
||||
}
|
||||
end
|
||||
|
||||
after :all do
|
||||
end
|
||||
|
||||
context ".info" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::Fop::Image.info(@source_image_url)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".exif" do
|
||||
it "should works" do
|
||||
result = Qiniu.get(@bucket, 'gogopher.jpg')
|
||||
result["url"].should_not be_empty
|
||||
puts result.inspect
|
||||
|
||||
code, data, headers = Qiniu::Fop::Image.exif(result["url"])
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
puts headers.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".mogrify_preview_url" do
|
||||
it "should works" do
|
||||
mogrify_preview_url = Qiniu::Fop::Image.mogrify_preview_url(@source_image_url, @mogrify_options)
|
||||
puts mogrify_preview_url.inspect
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
end # module Fop
|
||||
end # module Qiniu
|
||||
Executable
+150
@@ -0,0 +1,150 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
# vim: sw=2 ts=2
|
||||
|
||||
require 'digest/sha1'
|
||||
require 'spec_helper'
|
||||
require 'qiniu/auth'
|
||||
require 'qiniu/management'
|
||||
require 'qiniu'
|
||||
|
||||
module Qiniu
|
||||
module Storage
|
||||
describe Storage do
|
||||
|
||||
before :all do
|
||||
@bucket = 'rubysdk'
|
||||
|
||||
@key = Digest::SHA1.hexdigest((Time.now.to_i+rand(100)).to_s)
|
||||
@key = make_unique_key_in_bucket(@key)
|
||||
|
||||
@key2 = @key + rand(100).to_s
|
||||
end
|
||||
|
||||
after :all do
|
||||
end
|
||||
|
||||
### 准备数据
|
||||
context ".prepare_file" do
|
||||
it "should works" do
|
||||
pp = Auth::PutPolicy.new(@bucket, @key)
|
||||
code, data, raw_headers = Qiniu::Storage.upload_with_put_policy(
|
||||
pp,
|
||||
__FILE__
|
||||
)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
### 列举Bucket
|
||||
context ".buckets" do
|
||||
it "should works" do
|
||||
code, data = Storage.buckets
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".stat" do
|
||||
it "should works" do
|
||||
code, data = Storage.stat(@bucket, @key)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".get" do
|
||||
it "should works" do
|
||||
code, data = Storage.get(@bucket, @key)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".batch" do
|
||||
it "should works" do
|
||||
code, data = Storage.batch("stat", @bucket, [@key])
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".batch_stat" do
|
||||
it "should works" do
|
||||
code, data = Storage.batch_stat(@bucket, [@key])
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".batch_get" do
|
||||
it "should works" do
|
||||
code, data = Storage.batch_get(@bucket, [@key])
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".batch_copy" do
|
||||
it "should works" do
|
||||
code, data = Storage.batch_copy @bucket, @key, @bucket, @key2
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
|
||||
code, data = Storage.delete @bucket, @key2
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".batch_move" do
|
||||
it "should works" do
|
||||
code, data = Storage.batch_move @bucket, @key, @bucket, @key2
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
|
||||
code3, data3 = Storage.batch_move @bucket, @key2, @bucket, @key
|
||||
code3.should == 200
|
||||
puts data3.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".move" do
|
||||
it "should works" do
|
||||
code, data = Storage.move(@bucket, @key, @bucket, @key2)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
|
||||
code2, data2 = Storage.stat(@bucket, @key2)
|
||||
code2.should == 200
|
||||
puts data2.inspect
|
||||
|
||||
code3, data3 = Storage.move(@bucket, @key2, @bucket, @key)
|
||||
code3.should == 200
|
||||
puts data3.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".copy" do
|
||||
it "should works" do
|
||||
code, data = Storage.copy(@bucket, @key, @bucket, @key2)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
|
||||
code, data = Storage.delete(@bucket, @key2)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".delete" do
|
||||
it "should works" do
|
||||
code, data = Storage.delete(@bucket, @key)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
end # module Storage
|
||||
end # module Qiniu
|
||||
Executable
+53
@@ -0,0 +1,53 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'spec_helper'
|
||||
require 'qiniu/auth'
|
||||
require 'qiniu'
|
||||
require 'qiniu/misc'
|
||||
|
||||
module Qiniu
|
||||
module Misc
|
||||
describe Misc do
|
||||
|
||||
before :all do
|
||||
@bucket = 'rubysdk'
|
||||
end
|
||||
|
||||
after :all do
|
||||
end
|
||||
|
||||
context ".set_protected" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::Misc.set_protected(@bucket, 1)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".set_separator" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::Misc.set_separator(@bucket, "-")
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".set_style" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::Misc.set_style(@bucket, "small.jpg", "imageMogr/auto-orient/thumbnail/!120x120r/gravity/center/crop/!120x120/quality/80")
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".unset_style" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::Misc.unset_style(@bucket, "small.jpg")
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
end # module Misc
|
||||
end # module Qiniu
|
||||
@@ -0,0 +1,80 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
# vim: sw=2 ts=2
|
||||
|
||||
require 'spec_helper'
|
||||
require 'qiniu/auth'
|
||||
require 'qiniu'
|
||||
require 'qiniu/fop'
|
||||
|
||||
module Qiniu
|
||||
module Fop
|
||||
module Persistance
|
||||
describe Persistance do
|
||||
|
||||
before :all do
|
||||
@bucket = 'rubysdk'
|
||||
|
||||
pic_fname = "image_logo_for_test.png"
|
||||
@key = make_unique_key_in_bucket(pic_fname)
|
||||
|
||||
local_file = File.expand_path('../' + pic_fname, __FILE__)
|
||||
|
||||
### 检查测试文件存在性
|
||||
code, body, headers = Qiniu::Storage.stat(@bucket, @key)
|
||||
if code == 404 || code == 612 then
|
||||
# 文件不存在,尝试上传
|
||||
pp = Qiniu::Auth.PutPolicy.new(@bucket, @key)
|
||||
code, body, headers = Qiniu::Storage.upload_with_put_policy(
|
||||
pp,
|
||||
local_file
|
||||
)
|
||||
puts "Put a test file for Persistance cases"
|
||||
puts code.inspect
|
||||
puts body.inspect
|
||||
puts header.inspect
|
||||
end
|
||||
end
|
||||
|
||||
after :all do
|
||||
end
|
||||
|
||||
context ".pfop" do
|
||||
it "should works" do
|
||||
pp = Persistance::PfopPolicy.new(
|
||||
@bucket,
|
||||
@key,
|
||||
'imageView2/1/w/80/h/80', # fops
|
||||
'www.baidu.com' # notify_url
|
||||
)
|
||||
|
||||
code, data, headers = Qiniu::Fop::Persistance.pfop(pp)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".prefop" do
|
||||
it "should works" do
|
||||
code, data, headers = Qiniu::Fop::Persistance.prefop('fakePersistentId')
|
||||
code.should == 612
|
||||
puts code.inspect
|
||||
puts data.inspect
|
||||
puts headers.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".p1" do
|
||||
it "should works" do
|
||||
url = 'http://fake.qiniudn.com/fake.jpg'
|
||||
fop = 'imageView2/1/w/80/h/80'
|
||||
target_url = "#{url}?p/1/#{CGI.escape(fop).gsub('+', '%20')}"
|
||||
|
||||
p1_url = Qiniu::Fop::Persistance.generate_p1_url(url, fop)
|
||||
p1_url.should == target_url
|
||||
puts p1_url.inspect
|
||||
end
|
||||
end
|
||||
end
|
||||
end # module Persistance
|
||||
end # module Fop
|
||||
end # module Qiniu
|
||||
Executable
+311
@@ -0,0 +1,311 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'digest/sha1'
|
||||
require 'spec_helper'
|
||||
require 'qiniu'
|
||||
require 'qiniu/exceptions'
|
||||
|
||||
module Qiniu
|
||||
describe Qiniu do
|
||||
|
||||
before :all do
|
||||
@bucket = 'rubysdk'
|
||||
|
||||
@test_image_bucket = @bucket
|
||||
|
||||
@key = Digest::SHA1.hexdigest Time.now.to_s
|
||||
@key = make_unique_key_in_bucket(@key)
|
||||
|
||||
@key2 = @key + rand(100).to_s
|
||||
#@domain = @bucket + '.dn.qbox.me'
|
||||
|
||||
@test_image_key = 'image_logo_for_test.png'
|
||||
local_file = File.expand_path('./' + @test_image_key, File.dirname(__FILE__))
|
||||
puts local_file.inspect
|
||||
upopts = {:scope => @test_image_bucket, :expires_in => 3600, :customer => "why404@gmail.com"}
|
||||
uptoken = Qiniu.generate_upload_token(upopts)
|
||||
data = Qiniu.upload_file :uptoken => uptoken, :file => local_file, :bucket => @test_image_bucket, :key => @test_image_key
|
||||
puts data.inspect
|
||||
end
|
||||
|
||||
after :all do
|
||||
end
|
||||
|
||||
context ".buckets" do
|
||||
it "should works" do
|
||||
result = Qiniu.buckets
|
||||
expect(result).to_not be_empty
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".set_protected" do
|
||||
it "should works" do
|
||||
result = Qiniu.set_protected(@bucket, 1)
|
||||
expect(result).to eq(true)
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".set_separator" do
|
||||
it "should works" do
|
||||
result = Qiniu.set_separator(@bucket, "-")
|
||||
expect(result).to eq(true)
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".set_style" do
|
||||
it "should works" do
|
||||
result = Qiniu.set_style(@bucket, "small.jpg", "imageMogr/auto-orient/thumbnail/!120x120r/gravity/center/crop/!120x120/quality/80")
|
||||
expect(result).to eq(true)
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".unset_style" do
|
||||
it "should works" do
|
||||
result = Qiniu.unset_style(@bucket, "small.jpg")
|
||||
expect(result).to eq(true)
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".upload_file" do
|
||||
it "should works" do
|
||||
uptoken_opts = {:scope => @bucket, :escape => 0}
|
||||
upload_opts = {
|
||||
:uptoken => Qiniu.generate_upload_token(uptoken_opts),
|
||||
:file => __FILE__,
|
||||
:bucket => @bucket,
|
||||
:key => @key,
|
||||
:enable_crc32_check => true
|
||||
}
|
||||
result = Qiniu.upload_file(upload_opts)
|
||||
expect(result).to_not be_empty
|
||||
puts result.inspect
|
||||
end
|
||||
|
||||
it "should raise MissingArgsError" do
|
||||
uptoken_opts = {:scope => @bucket, :escape => 0}
|
||||
upload_opts = {
|
||||
:uptoken => Qiniu.generate_upload_token(uptoken_opts),
|
||||
:file => __FILE__,
|
||||
:key => @key,
|
||||
:enable_crc32_check => true
|
||||
}
|
||||
lambda { Qiniu.upload_file(upload_opts) }.should raise_error(MissingArgsError)
|
||||
end
|
||||
|
||||
it "should raise NoSuchFileError" do
|
||||
uptoken_opts = {:scope => @bucket, :escape => 0}
|
||||
upload_opts = {
|
||||
:uptoken => Qiniu.generate_upload_token(uptoken_opts),
|
||||
:file => 'no_this_file',
|
||||
:bucket => @bucket,
|
||||
:key => @key,
|
||||
:enable_crc32_check => true
|
||||
}
|
||||
lambda { Qiniu.upload_file(upload_opts) }.should raise_error(NoSuchFileError)
|
||||
end
|
||||
end
|
||||
|
||||
context ".resumable_upload_file" do
|
||||
it "should works" do
|
||||
# generate bigfile for testing
|
||||
localfile = "test_bigfile"
|
||||
File.open(localfile, "w"){|f| 5242888.times{f.write(rand(9).to_s)}}
|
||||
key = Digest::SHA1.hexdigest(localfile+Time.now.to_s)
|
||||
# generate the upload token
|
||||
uptoken_opts = {:scope => @bucket, :expires_in => 3600, :customer => "why404@gmail.com", :escape => 0}
|
||||
uptoken = Qiniu.generate_upload_token(uptoken_opts)
|
||||
# uploading
|
||||
upload_opts = {
|
||||
:uptoken => uptoken,
|
||||
:file => localfile,
|
||||
:bucket => @bucket,
|
||||
:key => key
|
||||
}
|
||||
#uploading
|
||||
result1 = Qiniu.upload_file(upload_opts)
|
||||
#drop the bigfile
|
||||
File.unlink(localfile) if File.exists?(localfile)
|
||||
#expect
|
||||
puts result1.inspect
|
||||
expect(result1).to_not be_empty
|
||||
#stat
|
||||
result2 = Qiniu.stat(@bucket, key)
|
||||
puts result2.inspect
|
||||
expect(result2).to_not be_empty
|
||||
#delete
|
||||
result3 = Qiniu.delete(@bucket, key)
|
||||
puts result3.inspect
|
||||
expect(result3).to eq(true)
|
||||
end
|
||||
end
|
||||
|
||||
context ".stat" do
|
||||
it "should works" do
|
||||
result = Qiniu.stat(@bucket, @key)
|
||||
expect(result).to_not be_empty
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".get" do
|
||||
it "should works" do
|
||||
result = Qiniu.get(@bucket, @key, "qiniu_spec.rb", 10)
|
||||
expect(result).to_not be_empty
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".download" do
|
||||
it "should works" do
|
||||
result = Qiniu.download(@bucket, @key, "rs_spec.rb", 10)
|
||||
expect(result).to_not be_empty
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".batch" do
|
||||
it "should works" do
|
||||
result = Qiniu.batch("stat", @bucket, [@key])
|
||||
expect(result).to_not be_empty
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".batch_stat" do
|
||||
it "should works" do
|
||||
result = Qiniu.batch_stat(@bucket, [@key])
|
||||
expect(result).to_not be_empty
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".batch_get" do
|
||||
it "should works" do
|
||||
result = Qiniu.batch_get(@bucket, [@key])
|
||||
expect(result).to_not be_empty
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".batch_download" do
|
||||
it "should works" do
|
||||
result = Qiniu.batch_download(@bucket, [@key])
|
||||
expect(result).to_not be_empty
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
=begin
|
||||
context ".batch_copy" do
|
||||
it "should works" do
|
||||
result = Qiniu.batch_copy [@bucket, @key, @bucket, @key2]
|
||||
result.should_not be_false
|
||||
|
||||
#result2 = Qiniu.stat(@bucket, @key2)
|
||||
#result2.should_not be_false
|
||||
end
|
||||
end
|
||||
|
||||
context ".batch_move" do
|
||||
it "should works" do
|
||||
result = Qiniu.batch_move [@bucket, @key, @bucket, @key2]
|
||||
result.should_not be_false
|
||||
|
||||
#result2 = Qiniu.stat(@bucket, @key2)
|
||||
#result2.should_not be_false
|
||||
|
||||
result3 = Qiniu.batch_move [@bucket, @key2, @bucket, @key]
|
||||
result3.should_not be_false
|
||||
end
|
||||
end
|
||||
=end
|
||||
|
||||
context ".move" do
|
||||
it "should works" do
|
||||
result = Qiniu.move(@bucket, @key, @bucket, @key2)
|
||||
expect(result).to eq(true)
|
||||
|
||||
result2 = Qiniu.stat(@bucket, @key2)
|
||||
expect(result2).to_not be_empty
|
||||
|
||||
result3 = Qiniu.move(@bucket, @key2, @bucket, @key)
|
||||
expect(result3).to eq(true)
|
||||
end
|
||||
end
|
||||
|
||||
context ".copy" do
|
||||
it "should works" do
|
||||
result = Qiniu.copy(@bucket, @key, @bucket, @key2)
|
||||
expect(result).to eq(true)
|
||||
|
||||
result3 = Qiniu.delete(@bucket, @key2)
|
||||
expect(result3).to eq(true)
|
||||
end
|
||||
end
|
||||
|
||||
context ".delete" do
|
||||
it "should works" do
|
||||
result = Qiniu.delete(@bucket, @key)
|
||||
expect(result).to eq(true)
|
||||
end
|
||||
end
|
||||
|
||||
context ".image_info" do
|
||||
it "should works" do
|
||||
data = Qiniu.get(@test_image_bucket, @test_image_key)
|
||||
expect(data).to_not be_empty
|
||||
puts data.inspect
|
||||
result = Qiniu.image_info(data["url"])
|
||||
expect(result).to_not be_empty
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".image_mogrify_save_as" do
|
||||
it "should works" do
|
||||
data = Qiniu.get(@test_image_bucket, @test_image_key)
|
||||
expect(data).to_not be_empty
|
||||
puts data.inspect
|
||||
|
||||
dest_key = "cropped-" + @test_image_key
|
||||
src_img_url = data["url"]
|
||||
mogrify_options = {
|
||||
:thumbnail => "!120x120>",
|
||||
:gravity => "center",
|
||||
:crop => "!120x120a0a0",
|
||||
:quality => 85,
|
||||
:rotate => 45,
|
||||
:format => "jpg",
|
||||
:auto_orient => true
|
||||
}
|
||||
result2 = Qiniu.image_mogrify_save_as(@test_image_bucket, dest_key, src_img_url, mogrify_options)
|
||||
expect(result2).to_not be_empty
|
||||
puts result2.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".generate_upload_token" do
|
||||
it "should works" do
|
||||
data = Qiniu.generate_upload_token({:scope => @bucket, :expires_in => 3600, :escape => 0})
|
||||
data.should_not be_empty
|
||||
puts data.inspect
|
||||
data.split(":").length.should == 3
|
||||
end
|
||||
end
|
||||
|
||||
context ".generate_download_token" do
|
||||
it "should works" do
|
||||
data = Qiniu.generate_download_token({:expires_in => 1, :pattern => 'http://*.dn.qbox.me/*'})
|
||||
data.should_not be_empty
|
||||
puts data.inspect
|
||||
data.split(":").length.should == 3
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
end # module Qiniu
|
||||
@@ -1,58 +0,0 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'spec_helper'
|
||||
require 'qiniu/rs/auth'
|
||||
|
||||
module Qiniu
|
||||
module RS
|
||||
describe Auth do
|
||||
|
||||
before :all do
|
||||
@username = "test@qbox.net"
|
||||
@password = "test"
|
||||
|
||||
code, data = Qiniu::RS::Auth.exchange_by_password!(@username, @password)
|
||||
code.should == 200
|
||||
data.should be_an_instance_of(Hash)
|
||||
data["access_token"].should_not be_empty
|
||||
data["refresh_token"].should_not be_empty
|
||||
data["refresh_token"].should_not be_empty
|
||||
|
||||
@access_token = data["access_token"]
|
||||
@refresh_token = data["refresh_token"]
|
||||
puts data.inspect
|
||||
end
|
||||
|
||||
context ".exchange_by_password" do
|
||||
it "should sign in failed when pass a non-existent username" do
|
||||
code, data = Qiniu::RS::Auth.exchange_by_password!("a_non_existent_user@example.com", "password")
|
||||
code.should == 401
|
||||
data["error_code"].should == 11
|
||||
data["error"].should == "failed_authentication"
|
||||
puts data.inspect
|
||||
end
|
||||
|
||||
it "should sign in failed when pass a wrong password" do
|
||||
code, data = Qiniu::RS::Auth.exchange_by_password!(@username, "a-wrong-password")
|
||||
code.should == 401
|
||||
data["error_code"].should == 11
|
||||
data["error"].should == "failed_authentication"
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".exchange_by_refresh_token" do
|
||||
it "should works" do
|
||||
@refresh_token.should_not be_empty
|
||||
code, data = Qiniu::RS::Auth.exchange_by_refresh_token!(@refresh_token)
|
||||
code.should == 200
|
||||
data["access_token"].should_not be_empty
|
||||
data["refresh_token"].should_not be_empty
|
||||
data["expires_in"].should_not be_zero
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,52 +0,0 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'spec_helper'
|
||||
require 'qiniu/rs/auth'
|
||||
require 'qiniu/rs'
|
||||
require 'qiniu/rs/image'
|
||||
|
||||
module Qiniu
|
||||
module RS
|
||||
describe Image do
|
||||
|
||||
before :each do
|
||||
=begin
|
||||
code, data = Qiniu::RS::Auth.exchange_by_password!("test@qbox.net", "test")
|
||||
code.should == 200
|
||||
data.should be_an_instance_of(Hash)
|
||||
data["access_token"].should_not be_empty
|
||||
data["refresh_token"].should_not be_empty
|
||||
data["refresh_token"].should_not be_empty
|
||||
puts data.inspect
|
||||
=end
|
||||
|
||||
@bucket = "test_images"
|
||||
@key = "image_logo_for_test.png"
|
||||
|
||||
local_file = File.expand_path('../' + @key, __FILE__)
|
||||
|
||||
put_url = Qiniu::RS.put_auth(10)
|
||||
put_url.should_not be_false
|
||||
put_url.should_not be_empty
|
||||
result = Qiniu::RS.upload :url => put_url,
|
||||
:file => local_file,
|
||||
:bucket => @bucket,
|
||||
:key => @key,
|
||||
:enable_crc32_check => true
|
||||
result.should be_true
|
||||
end
|
||||
|
||||
context ".info" do
|
||||
it "should works" do
|
||||
result = Qiniu::RS.get(@bucket, @key)
|
||||
result["url"].should_not be_empty
|
||||
puts result.inspect
|
||||
code, data = Qiniu::RS::Image.info(result["url"])
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,44 +0,0 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'spec_helper'
|
||||
require 'qiniu/rs/auth'
|
||||
require 'qiniu/rs/io'
|
||||
require 'digest/sha1'
|
||||
|
||||
module Qiniu
|
||||
module RS
|
||||
describe IO do
|
||||
|
||||
before :all do
|
||||
=begin
|
||||
code, data = Qiniu::RS::Auth.exchange_by_password!("test@qbox.net", "test")
|
||||
code.should == 200
|
||||
data.should be_an_instance_of(Hash)
|
||||
data["access_token"].should_not be_empty
|
||||
data["refresh_token"].should_not be_empty
|
||||
data["refresh_token"].should_not be_empty
|
||||
puts data.inspect
|
||||
=end
|
||||
|
||||
code2, data2 = Qiniu::RS::IO.put_auth()
|
||||
code2.should == 200
|
||||
data2["url"].should_not be_empty
|
||||
data2["expiresIn"].should_not be_zero
|
||||
puts data2.inspect
|
||||
|
||||
@put_url = data2["url"]
|
||||
@bucket = "test"
|
||||
@key = Digest::SHA1.hexdigest (Time.now.to_i+rand(100)).to_s
|
||||
end
|
||||
|
||||
context ".put_file" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::RS::IO.put_file(@put_url, __FILE__, @bucket, @key)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,118 +0,0 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'digest/sha1'
|
||||
require 'spec_helper'
|
||||
require 'qiniu/rs/auth'
|
||||
require 'qiniu/rs/io'
|
||||
require 'qiniu/rs/rs'
|
||||
|
||||
module Qiniu
|
||||
module RS
|
||||
describe RS do
|
||||
|
||||
before :all do
|
||||
=begin
|
||||
code, data = Qiniu::RS::Auth.exchange_by_password!("test@qbox.net", "test")
|
||||
code.should == 200
|
||||
data.should be_an_instance_of(Hash)
|
||||
data["access_token"].should_not be_empty
|
||||
data["refresh_token"].should_not be_empty
|
||||
data["refresh_token"].should_not be_empty
|
||||
puts data.inspect
|
||||
=end
|
||||
|
||||
code2, data2 = Qiniu::RS::IO.put_auth()
|
||||
code2.should == 200
|
||||
data2["url"].should_not be_empty
|
||||
data2["expiresIn"].should_not be_zero
|
||||
puts data2.inspect
|
||||
|
||||
@put_url = data2["url"]
|
||||
@bucket = "test"
|
||||
@key = Digest::SHA1.hexdigest (Time.now.to_i+rand(100)).to_s
|
||||
@domain = 'cdn.example.com'
|
||||
end
|
||||
|
||||
context "IO.put_file" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::RS::IO.put_file(@put_url, __FILE__, @bucket, @key)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".stat" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::RS::RS.stat(@bucket, @key)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".get" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::RS::RS.get(@bucket, @key, "rs_spec.rb", 1)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".batch" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::RS::RS.batch("stat", @bucket, [@key])
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".batch_stat" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::RS::RS.batch_stat(@bucket, [@key])
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".batch_get" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::RS::RS.batch_get(@bucket, [@key])
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".publish" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::RS::RS.publish(@domain, @bucket)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".unpublish" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::RS::RS.unpublish(@domain)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".delete" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::RS::RS.delete(@bucket, @key)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".drop" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::RS::RS.drop(@bucket)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,10 +0,0 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'spec_helper'
|
||||
require 'qiniu/rs/version'
|
||||
|
||||
describe Qiniu::RS do
|
||||
it "should has a VERSION" do
|
||||
Qiniu::RS::VERSION.should =~ /^\d+\.\d+\.\d+?$/
|
||||
end
|
||||
end
|
||||
@@ -1,153 +0,0 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'spec_helper'
|
||||
require 'qiniu/rs'
|
||||
|
||||
module Qiniu
|
||||
describe RS do
|
||||
|
||||
before :all do
|
||||
@bucket = 'qiniu_rs_test'
|
||||
@key = Digest::SHA1.hexdigest Time.now.to_s
|
||||
@domain = 'cdn.example.com'
|
||||
end
|
||||
|
||||
=begin
|
||||
context ".login!" do
|
||||
it "should works" do
|
||||
result = Qiniu::RS.login!("test@qbox.net", "test")
|
||||
result.should be_true
|
||||
end
|
||||
end
|
||||
=end
|
||||
|
||||
context ".put_auth" do
|
||||
it "should works" do
|
||||
result = Qiniu::RS.put_auth(10)
|
||||
result.should_not be_false
|
||||
result.should_not be_empty
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".upload" do
|
||||
it "should works" do
|
||||
put_url = Qiniu::RS.put_auth(10)
|
||||
put_url.should_not be_false
|
||||
put_url.should_not be_empty
|
||||
puts put_url.inspect
|
||||
result = Qiniu::RS.upload :url => put_url,
|
||||
:file => __FILE__,
|
||||
:bucket => @bucket,
|
||||
:key => @key,
|
||||
:enable_crc32_check => true
|
||||
result.should be_true
|
||||
end
|
||||
end
|
||||
|
||||
context ".stat" do
|
||||
it "should works" do
|
||||
result = Qiniu::RS.stat(@bucket, @key)
|
||||
result.should_not be_false
|
||||
result.should_not be_empty
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".get" do
|
||||
it "should works" do
|
||||
result = Qiniu::RS.get(@bucket, @key, "rs_spec.rb", 10)
|
||||
result.should_not be_false
|
||||
result.should_not be_empty
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".download" do
|
||||
it "should works" do
|
||||
result = Qiniu::RS.download(@bucket, @key, "rs_spec.rb", 10)
|
||||
result.should_not be_false
|
||||
result.should_not be_empty
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".batch" do
|
||||
it "should works" do
|
||||
result = Qiniu::RS.batch("stat", @bucket, [@key])
|
||||
result.should_not be_false
|
||||
result.should_not be_empty
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".batch_stat" do
|
||||
it "should works" do
|
||||
result = Qiniu::RS.batch_stat(@bucket, [@key])
|
||||
result.should_not be_false
|
||||
result.should_not be_empty
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".batch_get" do
|
||||
it "should works" do
|
||||
result = Qiniu::RS.batch_get(@bucket, [@key])
|
||||
result.should_not be_false
|
||||
result.should_not be_empty
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".batch_download" do
|
||||
it "should works" do
|
||||
result = Qiniu::RS.batch_download(@bucket, [@key])
|
||||
result.should_not be_false
|
||||
result.should_not be_empty
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".publish" do
|
||||
it "should works" do
|
||||
result = Qiniu::RS.publish(@domain, @bucket)
|
||||
result.should_not be_false
|
||||
end
|
||||
end
|
||||
|
||||
context ".unpublish" do
|
||||
it "should works" do
|
||||
result = Qiniu::RS.unpublish(@domain)
|
||||
result.should_not be_false
|
||||
end
|
||||
end
|
||||
|
||||
context ".delete" do
|
||||
it "should works" do
|
||||
result = Qiniu::RS.delete(@bucket, @key)
|
||||
result.should_not be_false
|
||||
end
|
||||
end
|
||||
|
||||
context ".drop" do
|
||||
it "should works" do
|
||||
result = Qiniu::RS.drop(@bucket)
|
||||
result.should_not be_false
|
||||
end
|
||||
end
|
||||
|
||||
context ".image_info" do
|
||||
it "should works" do
|
||||
data = Qiniu::RS.get("test_images", "image_logo_for_test.png")
|
||||
data.should_not be_false
|
||||
data.should_not be_empty
|
||||
puts data.inspect
|
||||
result = Qiniu::RS.image_info(data["url"])
|
||||
result.should_not be_false
|
||||
result.should_not be_empty
|
||||
puts result.inspect
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,29 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'spec_helper'
|
||||
require 'qiniu/tokens/qbox_token'
|
||||
|
||||
module Qiniu
|
||||
module RS
|
||||
describe QboxToken do
|
||||
before :all do
|
||||
@qbox_token = QboxToken.new(:url => 'www.qiniu.com?key1=value1',
|
||||
:params => { :key2 => 'value2' })
|
||||
@qbox_token.access_key = 'access_key'
|
||||
@qbox_token.secret_key = 'secret_key'
|
||||
end
|
||||
|
||||
context "#generate_token" do
|
||||
it "should generate token" do
|
||||
@qbox_token.generate_token.should_not be_empty
|
||||
end
|
||||
end
|
||||
|
||||
context "#generate_signature" do
|
||||
it "should generate signature" do
|
||||
@qbox_token.generate_signature.should == "www.qiniu.com?key1=value1\nkey2=value2"
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
Executable
+301
@@ -0,0 +1,301 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
# vim: sw=2 ts=2
|
||||
|
||||
require 'spec_helper'
|
||||
require 'qiniu/auth'
|
||||
require 'qiniu/storage'
|
||||
require 'digest/sha1'
|
||||
|
||||
module Qiniu
|
||||
module Storage
|
||||
describe Storage do
|
||||
|
||||
before :all do
|
||||
@bucket = 'rubysdk'
|
||||
|
||||
@key = Digest::SHA1.hexdigest((Time.now.to_i+rand(100)).to_s)
|
||||
@key = make_unique_key_in_bucket(@key)
|
||||
puts "key=#{@key}"
|
||||
|
||||
@localfile_5m = "5M.txt"
|
||||
File.open(@localfile_5m, "w"){|f| 5242888.times{ f.write(rand(9).to_s) }}
|
||||
@key_5m = Digest::SHA1.hexdigest(@localfile_5m+Time.now.to_s)
|
||||
@key_5m = make_unique_key_in_bucket(@key_5m)
|
||||
puts "key_5m=#{@key_5m}"
|
||||
|
||||
@localfile_4m = "4M.txt"
|
||||
File.open(@localfile_4m, "w"){|f| (1 << 22).times{ f.write(rand(9).to_s) }}
|
||||
@key_4m = Digest::SHA1.hexdigest(@localfile_4m+Time.now.to_s)
|
||||
@key_4m = make_unique_key_in_bucket(@key_4m)
|
||||
puts "key_4m=#{@key_4m}"
|
||||
|
||||
@localfile_8m = "8M.txt"
|
||||
File.open(@localfile_8m, "w"){|f| (1 << 23).times{ f.write(rand(9).to_s) }}
|
||||
@key_8m = Digest::SHA1.hexdigest(@localfile_8m+Time.now.to_s)
|
||||
@key_8m = make_unique_key_in_bucket(@key_8m)
|
||||
puts "key_8m=#{@key_8m}"
|
||||
|
||||
@localfile_1m = "1M.txt"
|
||||
File.open(@localfile_1m, "w"){|f| (1 << 20).times{ f.write(rand(9).to_s) }}
|
||||
@key_1m = Digest::SHA1.hexdigest(@localfile_1m+Time.now.to_s)
|
||||
@key_1m = make_unique_key_in_bucket(@key_1m)
|
||||
puts "key_1m=#{@key_1m}"
|
||||
end
|
||||
|
||||
after :all do
|
||||
### 清除本地临时文件
|
||||
File.unlink(@localfile_5m) if File.exists?(@localfile_5m)
|
||||
File.unlink(@localfile_4m) if File.exists?(@localfile_4m)
|
||||
File.unlink(@localfile_8m) if File.exists?(@localfile_8m)
|
||||
File.unlink(@localfile_1m) if File.exists?(@localfile_1m)
|
||||
end
|
||||
|
||||
### 测试单文件直传
|
||||
context ".upload_with_token" do
|
||||
it "should works" do
|
||||
upopts = {:scope => @bucket, :expires_in => 3600, :customer => "why404@gmail.com"}
|
||||
uptoken = Qiniu.generate_upload_token(upopts)
|
||||
code, data, raw_headers = Qiniu::Storage.upload_with_token(
|
||||
uptoken,
|
||||
__FILE__,
|
||||
@bucket,
|
||||
@key,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
true
|
||||
)
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
puts raw_headers.inspect
|
||||
end
|
||||
end
|
||||
|
||||
context ".stat" do
|
||||
it "should exists" do
|
||||
code, data = Qiniu::Storage.stat(@bucket, @key)
|
||||
puts data.inspect
|
||||
code.should == 200
|
||||
end
|
||||
end
|
||||
|
||||
context ".delete" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::Storage.delete(@bucket, @key)
|
||||
puts data.inspect
|
||||
code.should == 200
|
||||
end
|
||||
end
|
||||
|
||||
context ".upload_with_token_2" do
|
||||
it "should works" do
|
||||
upopts = {:scope => @bucket, :expires_in => 3600, :endUser => "why404@gmail.com"}
|
||||
uptoken = Qiniu.generate_upload_token(upopts)
|
||||
|
||||
code, data, raw_headers = Qiniu::Storage.upload_with_token_2(
|
||||
uptoken,
|
||||
__FILE__,
|
||||
@key
|
||||
)
|
||||
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
puts raw_headers.inspect
|
||||
end
|
||||
end # .upload_with_token_2
|
||||
|
||||
context ".stat" do
|
||||
it "should exists" do
|
||||
code, data = Qiniu::Storage.stat(@bucket, @key)
|
||||
puts data.inspect
|
||||
code.should == 200
|
||||
end
|
||||
end
|
||||
|
||||
context ".delete" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::Storage.delete(@bucket, @key)
|
||||
puts data.inspect
|
||||
code.should == 200
|
||||
end
|
||||
end
|
||||
|
||||
context ".upload_with_put_policy" do
|
||||
it "should works" do
|
||||
pp = Qiniu::Auth::PutPolicy.new(@bucket, @key)
|
||||
pp.end_user = "why404@gmail.com"
|
||||
puts 'put_policy=' + pp.to_json
|
||||
|
||||
code, data, raw_headers = Qiniu::Storage.upload_with_put_policy(
|
||||
pp,
|
||||
__FILE__,
|
||||
@key + '-not-equal'
|
||||
)
|
||||
code.should_not == 200
|
||||
puts data.inspect
|
||||
puts raw_headers.inspect
|
||||
|
||||
code, data, raw_headers = Qiniu::Storage.upload_with_put_policy(
|
||||
pp,
|
||||
__FILE__,
|
||||
@key
|
||||
)
|
||||
|
||||
code.should == 200
|
||||
puts data.inspect
|
||||
puts raw_headers.inspect
|
||||
end
|
||||
end # .upload_with_put_policy
|
||||
|
||||
context ".stat" do
|
||||
it "should exists" do
|
||||
code, data = Qiniu::Storage.stat(@bucket, @key)
|
||||
puts data.inspect
|
||||
code.should == 200
|
||||
end
|
||||
end
|
||||
|
||||
context ".delete" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::Storage.delete(@bucket, @key)
|
||||
puts data.inspect
|
||||
code.should == 200
|
||||
end
|
||||
end
|
||||
|
||||
### 测试断点续上传
|
||||
context ".resumable_upload_with_token" do
|
||||
it "should works" do
|
||||
upopts = {:scope => @bucket, :expires_in => 3600, :customer => "why404@gmail.com"}
|
||||
uptoken = Qiniu.generate_upload_token(upopts)
|
||||
code, data, raw_headers = Qiniu::Storage.resumable_upload_with_token(
|
||||
uptoken,
|
||||
@localfile_5m,
|
||||
@bucket,
|
||||
@key_5m
|
||||
)
|
||||
(code/100).should == 2
|
||||
puts data.inspect
|
||||
puts raw_headers.inspect
|
||||
puts "key_5m=#{@key_5m}"
|
||||
end
|
||||
end
|
||||
|
||||
context ".stat" do
|
||||
it "should exists" do
|
||||
code, data = Qiniu::Storage.stat(@bucket, @key_5m)
|
||||
puts data.inspect
|
||||
code.should == 200
|
||||
end
|
||||
end
|
||||
|
||||
context ".delete" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::Storage.delete(@bucket, @key_5m)
|
||||
puts data.inspect
|
||||
code.should == 200
|
||||
end
|
||||
end
|
||||
|
||||
context ".resumable_upload_with_token2" do
|
||||
it "should works" do
|
||||
upopts = {:scope => @bucket, :expires_in => 3600, :customer => "why404@gmail.com"}
|
||||
uptoken = Qiniu.generate_upload_token(upopts)
|
||||
code, data, raw_headers = Qiniu::Storage.resumable_upload_with_token(
|
||||
uptoken,
|
||||
@localfile_4m,
|
||||
@bucket,
|
||||
@key_4m
|
||||
)
|
||||
(code/100).should == 2
|
||||
puts data.inspect
|
||||
puts raw_headers.inspect
|
||||
puts "key_4m=#{@key_4m}"
|
||||
end
|
||||
end
|
||||
|
||||
context ".stat" do
|
||||
it "should exists" do
|
||||
code, data = Qiniu::Storage.stat(@bucket, @key_4m)
|
||||
puts data.inspect
|
||||
code.should == 200
|
||||
end
|
||||
end
|
||||
|
||||
context ".delete" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::Storage.delete(@bucket, @key_4m)
|
||||
puts data.inspect
|
||||
code.should == 200
|
||||
end
|
||||
end
|
||||
|
||||
context ".resumable_upload_with_token3" do
|
||||
it "should works" do
|
||||
upopts = {:scope => @bucket, :expires_in => 3600, :customer => "why404@gmail.com"}
|
||||
uptoken = Qiniu.generate_upload_token(upopts)
|
||||
code, data, raw_headers = Qiniu::Storage.resumable_upload_with_token(
|
||||
uptoken,
|
||||
@localfile_8m,
|
||||
@bucket,
|
||||
@key_8m
|
||||
)
|
||||
(code/100).should == 2
|
||||
puts data.inspect
|
||||
puts raw_headers.inspect
|
||||
puts "key_8m=#{@key_8m}"
|
||||
end
|
||||
end
|
||||
|
||||
context ".stat" do
|
||||
it "should exists" do
|
||||
code, data = Qiniu::Storage.stat(@bucket, @key_8m)
|
||||
puts data.inspect
|
||||
code.should == 200
|
||||
end
|
||||
end
|
||||
|
||||
context ".delete" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::Storage.delete(@bucket, @key_8m)
|
||||
puts data.inspect
|
||||
code.should == 200
|
||||
end
|
||||
end
|
||||
|
||||
context ".resumable_upload_with_token4" do
|
||||
it "should works" do
|
||||
upopts = {:scope => @bucket, :expires_in => 3600, :customer => "why404@gmail.com"}
|
||||
uptoken = Qiniu.generate_upload_token(upopts)
|
||||
code, data, raw_headers = Qiniu::Storage.resumable_upload_with_token(
|
||||
uptoken,
|
||||
@localfile_1m,
|
||||
@bucket,
|
||||
@key_1m
|
||||
)
|
||||
(code/100).should == 2
|
||||
puts data.inspect
|
||||
puts raw_headers.inspect
|
||||
puts "key_1m=#{@key_1m}"
|
||||
end
|
||||
end
|
||||
|
||||
context ".stat" do
|
||||
it "should exists" do
|
||||
code, data = Qiniu::Storage.stat(@bucket, @key_1m)
|
||||
puts data.inspect
|
||||
code.should == 200
|
||||
end
|
||||
end
|
||||
|
||||
context ".delete" do
|
||||
it "should works" do
|
||||
code, data = Qiniu::Storage.delete(@bucket, @key_1m)
|
||||
puts data.inspect
|
||||
code.should == 200
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
end # module Storage
|
||||
end # module Qiniu
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
require 'spec_helper'
|
||||
require 'fakeweb'
|
||||
require 'qiniu/rs/utils'
|
||||
require 'qiniu/utils'
|
||||
|
||||
module Qiniu
|
||||
module RS
|
||||
@@ -26,18 +26,18 @@ module Qiniu
|
||||
context ".send_request_with" do
|
||||
it "should works" do
|
||||
FakeWeb.allow_net_connect = false
|
||||
FakeWeb.register_uri(:get, "http://docs.qiniutek.com/", :body => {:abc => 123}.to_json)
|
||||
res = Utils.send_request_with 'http://docs.qiniutek.com/', nil, :method => :get
|
||||
res.should == [200, {"abc" => 123}]
|
||||
FakeWeb.register_uri(:get, "http://develoepr.qiniu.com/", :body => {:abc => 123}.to_json)
|
||||
res = Utils.send_request_with 'http://develoepr.qiniu.com/', nil, :method => :get
|
||||
res.should == [200, {"abc" => 123}, {}]
|
||||
end
|
||||
|
||||
[400, 500].each do |code|
|
||||
context "upstream return http #{code}" do
|
||||
it "should raise RestClient::RequestFailed" do
|
||||
FakeWeb.allow_net_connect = false
|
||||
FakeWeb.register_uri(:get, "http://docs.qiniutek.com/", :status => code)
|
||||
FakeWeb.register_uri(:get, "http://develoepr.qiniu.com/", :status => code)
|
||||
lambda {
|
||||
res = Utils.send_request_with 'http://docs.qiniutek.com/', nil, :method => :get
|
||||
res = Utils.send_request_with 'http://develoepr.qiniu.com/', nil, :method => :get
|
||||
}.should raise_error RestClient::RequestFailed
|
||||
end
|
||||
end
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'spec_helper'
|
||||
require 'qiniu/version'
|
||||
|
||||
describe Qiniu::Version do
|
||||
it "should has a VERSION" do
|
||||
Qiniu::Version.to_s.should =~ /^\d+\.\d+\.\d+?$/
|
||||
end
|
||||
end
|
||||
+13
-3
@@ -1,12 +1,22 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
|
||||
require 'bundler/setup'
|
||||
require 'qiniu/rs'
|
||||
require 'qiniu'
|
||||
require 'rspec'
|
||||
|
||||
RSpec.configure do |config|
|
||||
config.before :all do
|
||||
Qiniu::RS.establish_connection! :access_key => "3fPHl_SLkPXdioqI_A8_NGngPWVJhlDk2ktRjogH",
|
||||
:secret_key => "bXTPMDJrVYRJUiSDRFtFYwycVD_mjXxYWrCYlDHy"
|
||||
Qiniu.establish_connection! :access_key => ENV["QINIU_ACCESS_KEY"], :secret_key => ENV["QINIU_SECRET_KEY"]
|
||||
end
|
||||
config.before :each, :not_set_ak_sk => true do
|
||||
Qiniu.establish_connection! :access_key => nil, :secret_key => nil
|
||||
end
|
||||
end
|
||||
|
||||
def make_unique_bucket (bucket)
|
||||
bucket + "-" + ENV["QINIU_ACCESS_KEY"][0, 8]
|
||||
end # make_unique_bucket
|
||||
|
||||
def make_unique_key_in_bucket (key)
|
||||
"#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}-" + key
|
||||
end # make_unique_key_in_bucket
|
||||
|
||||
Reference in New Issue
Block a user