Compare commits

...
69 Commits
Author SHA1 Message Date
xushiwei 2cbb175423 Merge pull request #26 from why404/release/v3.2.2
fix up 701
2012-12-04 22:32:53 -08:00
404 a8a8f63887 fix up 701 2012-12-05 14:00:12 +08:00
404 64cf9b5d3f Merge pull request #24 from hayeah/master
Fixes Qiniu::RS::Exception Issue
2012-11-29 01:53:46 -08:00
Howard Yeh 1a73c39ffb Don't override to_s of Exception with inspect.
This causes infinite recursion.
2012-11-27 18:52:41 +08:00
xushiwei 864076b9ec Merge pull request #21 from why404/release/v3.2.0
Release/v3.2.0 - allow upload calback api
2012-11-08 03:01:27 -08:00
404 bb6efd4e0d upload auto-rorate supported 2012-11-07 17:28:48 +08:00
404 ef1739cb2a v3.2.0 2012-11-06 23:19:14 +08:00
404 611837b137 Merge branch 'feature/allow_upload_callback_api' into develop 2012-11-06 23:17:16 +08:00
404 000eef8870 update unit tests 2012-11-06 23:16:40 +08:00
404 bacf83dd3c allow upload callback api 2012-11-06 22:09:19 +08:00
xushiwei b8ad8bd7a1 Merge pull request #20 from why404/develop
v3.1.0 - resumable upload support
2012-10-15 08:51:52 -07:00
404 38a0877b66 Merge branch 'release/v3.1.0' 2012-10-08 13:04:30 +08:00
404 241a16c40b Merge branch 'feature/resumable_upload' into develop 2012-10-08 13:00:56 +08:00
404 9a5a27429d add resumable upload and all tests(63 examples) passed 2012-10-08 12:59:30 +08:00
404 8011d6d837 all resumable uploading tests are passed 2012-10-03 12:02:38 +08:00
404 2451b5b51f update qiniu/rs/exceptions 2012-10-02 23:40:26 +08:00
404 bd34ea428e add Qiniu::RS::UP module 2012-10-02 18:47:19 +08:00
404 fa40449b12 added UploadFailedError 2012-09-27 20:22:51 +08:00
404 cf8a38faa0 Merge branch 'master' into develop 2012-09-25 13:44:54 +08:00
xushiwei f3dd759a5b Merge pull request #18 from why404/master
避免gems依赖包冲突,调整为x.y(不加.z)更为宽松的依赖策略
2012-09-12 06:25:36 -07:00
404 1072b1ebab Merge branch 'hotfix/v3.0.6' into develop 2012-09-12 16:19:55 +08:00
404 df68455eed Merge branch 'hotfix/v3.0.6' 2012-09-12 16:19:44 +08:00
404 ec58895ca7 Gemfile update 2012-09-12 16:19:32 +08:00
xushiwei 4f9ca6e468 Merge pull request #16 from why404/master
publish v3.0.4 for hotfix
2012-09-03 03:58:02 -07:00
404 93a78047c1 v3.0.5 2012-09-03 18:18:21 +08:00
404 f304a2cb67 Merge branch 'master' into develop 2012-09-03 18:14:51 +08:00
404 c2a30d5a01 version 3.0.5 2012-09-03 18:14:42 +08:00
404 7432857c5a Merge branch 'hotfix/v3.0.5' into develop 2012-09-03 18:12:25 +08:00
404 1d50e3aa54 Merge branch 'hotfix/v3.0.5' 2012-09-03 18:12:00 +08:00
404 13e1051b87 fixed rescue for ruby 1.8 2012-09-03 18:10:58 +08:00
404 7c1fd4d207 Merge branch 'master' into develop 2012-08-19 02:03:33 +08:00
404 7b628281d3 changed test env 2012-08-19 02:03:23 +08:00
404 263ea64367 Merge remote-tracking branch 'qiniu/master' into develop 2012-08-19 01:59:21 +08:00
404 2dfd3da781 Merge remote-tracking branch 'qiniu/master' 2012-08-19 01:59:03 +08:00
xushiwei 1af173d04f Merge pull request #15 from huobazi/master
修正 Qiniu::RS.generate_upload_toke 对参数处理和文档描述不一致
2012-08-18 10:25:03 -07:00
huobazi b176c7a604 文档中描述 Qiniu::RS.generate_upload_toke的参数为可选,默认值为3600,但代码中实际的处理并没有考虑参数未传值时取默认值
ref: http://docs.qiniutek.com/v3/sdk/ruby/#upload
2012-08-18 23:22:37 +08:00
404 9c719cc8e5 Merge branch 'hotfix/v3.0.3' into develop 2012-08-18 00:00:18 +08:00
404 e8a1343328 Merge branch 'hotfix/v3.0.3' 2012-08-18 00:00:01 +08:00
xushiwei 88b56daabd Merge pull request #14 from why404/hotfix/v3.0.3
Hotfix/v3.0.3 - doc link version
2012-08-17 08:50:51 -07:00
404 bab0f4a602 verion updated 2012-08-17 23:22:03 +08:00
xushiwei 1b9077a7dd Merge pull request #13 from why404/hotfix/v3.0.2
update spec - removed pub2 test
2012-08-16 20:11:40 -07:00
404 64ddbbe831 Merge branch 'hotfix/v3.0.2' into develop 2012-08-17 09:44:12 +08:00
404 36d5fc0684 Merge branch 'hotfix/v3.0.2' 2012-08-17 09:43:43 +08:00
404 490f359a17 update spec 2012-08-17 09:40:15 +08:00
xushiwei 01bd208627 Merge pull request #12 from why404/develop
add up, pub, eu and rsplus supported
2012-08-15 06:26:44 -07:00
404 d0c69c2255 updated doc 2012-08-15 20:20:34 +08:00
404 7e4aff00a1 Merge branch 'develop' 2012-08-15 18:53:51 +08:00
404 93ca5c5009 changed unstyle to unset_style 2012-08-15 18:53:25 +08:00
404 46144f145c Merge branch 'release/v3.0.0' into develop 2012-08-14 18:02:59 +08:00
404 b2ddd186aa Merge branch 'release/v3.0.0' 2012-08-14 18:02:31 +08:00
404 9f07e8d236 added watermarking and all tests passed (staging env) 2012-08-14 18:02:05 +08:00
404 4f04812b5c Merge branch 'feature/doc' into develop 2012-08-14 17:58:50 +08:00
404 fcc6870f2e updated doc 2012-08-14 17:58:34 +08:00
404 2bd158c1fe doc 2012-08-14 11:16:48 +08:00
404 556210548b callback_body_type 2012-08-14 00:06:42 +08:00
404 3b58147e70 rs spec 2012-08-13 23:42:35 +08:00
404 6746a8eeeb updated gemlock 2012-08-13 23:25:39 +08:00
404 da0d8d5ef8 fixed digest post data 2012-08-13 16:50:40 +08:00
404 1a950e8f85 uptoken field rename 2012-08-03 17:08:19 +08:00
404 d1b3f3c080 fixed io spec 2012-08-03 09:49:07 +08:00
404 46eb6e3d58 upload_with_token spec 2012-08-02 14:23:43 +08:00
404 8e86a92080 updated watermark tests 2012-08-02 13:59:02 +08:00
404 33447b0d5f new uptoken 2012-08-02 13:36:46 +08:00
404 e7f64fabae fixed io_spec.rb 2012-08-01 18:04:10 +08:00
404 1d63970688 rsplus/pub/eu fix 2012-08-01 11:58:43 +08:00
404 83475e594a end user module 2012-07-31 16:26:43 +08:00
404 9210c7fc32 pub 2012-07-31 12:29:22 +08:00
404 1a9dfeb9a7 uptoken 2012-07-31 10:14:10 +08:00
404 da3bdd362e added buckets 2012-07-30 15:37:52 +08:00
30 changed files with 1539 additions and 197 deletions
+31
View File
@@ -0,0 +1,31 @@
## CHANGE LOG
### 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)
+16 -16
View File
@@ -1,37 +1,37 @@
PATH
remote: .
specs:
qiniu-rs (2.3.3)
json (~> 1.7.3)
qiniu-rs (3.2.2)
json (~> 1.7)
mime-types (~> 1.19)
rest-client (~> 1.6.7)
ruby-hmac (~> 0.4.0)
rest-client (~> 1.6)
ruby-hmac (~> 0.4)
GEM
remote: https://rubygems.org/
specs:
diff-lcs (1.1.3)
fakeweb (1.3.0)
json (1.7.4)
json (1.7.5)
mime-types (1.19)
rake (0.9.2.2)
rake (10.0.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)
rspec (2.12.0)
rspec-core (~> 2.12.0)
rspec-expectations (~> 2.12.0)
rspec-mocks (~> 2.12.0)
rspec-core (2.12.1)
rspec-expectations (2.12.0)
diff-lcs (~> 1.1.3)
rspec-mocks (2.10.1)
rspec-mocks (2.12.0)
ruby-hmac (0.4.0)
PLATFORMS
ruby
DEPENDENCIES
fakeweb (~> 1.3.0)
fakeweb (~> 1.3)
qiniu-rs!
rake (~> 0.9.2.2)
rspec (~> 2.10.0)
rake (>= 0.9)
rspec (~> 2.11)
+2 -2
View File
@@ -2,7 +2,7 @@
# 关于
此 Ruby SDK 适用于 Ruby 1.8.x, 1.9.x, jruby, rbx, ree 版本,基于 [七牛云存储官方API](http://docs.qiniutek.com/v2/api/) 构建。使用此 SDK 构建您的网络应用程序,能让您以非常便捷地方式将数据安全地存储到七牛云存储上。无论您的网络应用是一个网站程序,还是包括从云端(服务端程序)到终端(手持设备应用)的架构的服务或应用,通过七牛云存储及其 SDK,都能让您应用程序的终端用户高速上传和下载,同时也让您的服务端更加轻盈。
此 Ruby SDK 适用于 Ruby 1.8.x, 1.9.x, jruby, rbx, ree 版本,基于 [七牛云存储官方API](http://docs.qiniutek.com/v3/api/) 构建。使用此 SDK 构建您的网络应用程序,能让您以非常便捷地方式将数据安全地存储到七牛云存储上。无论您的网络应用是一个网站程序,还是包括从云端(服务端程序)到终端(手持设备应用)的架构的服务或应用,通过七牛云存储及其 SDK,都能让您应用程序的终端用户高速上传和下载,同时也让您的服务端更加轻盈。
## 安装
@@ -20,7 +20,7 @@
## 使用
参考文档:[七牛云存储 Ruby SDK 使用指南](http://docs.qiniutek.com/v2/sdk/ruby/)
参考文档:[七牛云存储 Ruby SDK 使用指南](http://docs.qiniutek.com/v3/sdk/ruby/)
## 贡献代码
+437 -47
View File
@@ -4,7 +4,7 @@ title: Ruby SDK 使用指南 | 七牛云存储
# Ruby SDK 使用指南
此 Ruby SDK 适用于 Ruby 1.8.x, 1.9.x, jruby, rbx, ree 版本,基于 [七牛云存储官方API](/v2/api/) 构建。使用此 SDK 构建您的网络应用程序,能让您以非常便捷地方式将数据安全地存储到七牛云存储上。无论您的网络应用是一个网站程序,还是包括从云端(服务端程序)到终端(手持设备应用)的架构的服务或应用,通过七牛云存储及其 SDK,都能让您应用程序的终端用户高速上传和下载,同时也让您的服务端更加轻盈。
此 Ruby SDK 适用于 Ruby 1.8.x, 1.9.x, jruby, rbx, ree 版本,基于 [七牛云存储官方API](/v3/api/) 构建。使用此 SDK 构建您的网络应用程序,能让您以非常便捷地方式将数据安全地存储到七牛云存储上。无论您的网络应用是一个网站程序,还是包括从云端(服务端程序)到终端(手持设备应用)的架构的服务或应用,通过七牛云存储及其 SDK,都能让您应用程序的终端用户高速上传和下载,同时也让您的服务端更加轻盈。
七牛云存储 Ruby SDK 源码地址:[https://github.com/qiniu/ruby-sdk](https://github.com/qiniu/ruby-sdk)
@@ -15,26 +15,39 @@ title: Ruby SDK 使用指南 | 七牛云存储
- [应用接入](#establish_connection!)
- [Ruby On Rails 应用初始化设置](#ror-init)
- [上传文件](#upload)
- [服务端上传流程](#upload-server-side)
- [客户端上传流程](#upload-client-side)
- [获取用于上传文件的临时授权URL](#put_auth)
- [获取用于上传文件的临时授权凭证](#generate-upload-token)
- [服务端上传文件](#upload-server-side)
- [断点续上传](#resumable-upload)
- [针对 NotFound 场景处理](#upload-file-for-not-found)
- [客户端直传文件](#upload-client-side)
- [查看文件属性信息](#stat)
- [获取文件下载链接(含文件属性信息)](#get)
- [只获取文件下载链接](#download)
- [删除指定文件](#delete)
- [删除所有文件(单个“表”](#drop)
- [删除所有文件(单个 bucket](#drop)
- [批量操作](#batch)
- [批量获取文件属性信息(含下载链接)](#batch_get)
- [批量获取文件下载链接](#batch_download)
- [批量删除文件](#batch_delete)
- [创建公开外链](#publish)
- [取消公开外链](#unpublish)
- [Bucket(资源表)管理](#buckets)
- [创建 Bucket](#mkbucket)
- [列出所有 Bucket](#list-all-buckets)
- [访问控制](#set-protected)
- [图像处理](#op-image)
- [查看图片属性信息](#image_info)
- [查看图片EXIF信息](#image_exif)
- [获取指定规格的缩略图预览地址](#image_preview_url)
- [高级图像处理(缩略、裁剪、旋转、转化)](#image_mogrify_preview_url)
- [高级图像处理(缩略、裁剪、旋转、转化)并持久化](#image_mogrify_save_as)
- [高级图像处理(水印)](#image-watermarking)
- [水印准备工作](#watermarking-pre-work)
- [设置原图保护](#watermarking-set-protected)
- [设置水印预览图URL分隔符](#watermarking-set-sep)
- [设置水印预览图规格别名](#watermarking-set-style)
- [设置水印模板](#watermarking-set-template)
- [获取水印模板](#watermarking-get-template)
- [贡献代码](#Contributing)
- [许可证](#License)
@@ -95,21 +108,76 @@ title: Ruby SDK 使用指南 | 七牛云存储
### 上传文件
<a name="upload-server-side"></a>
<a name="generate-upload-token"></a>
#### 服务端上传流程
#### 获取用于上传文件的临时授权凭证
通过 `Qiniu::RS.put_file()` 方法可在客户方的业务服务器上直接往七牛云存储上传文件。该函数规格如下:
要上传一个文件,首先需要调用 SDK 提供的 `Qiniu::RS.generate_upload_token` 函数来获取一个经过授权用于临时匿名上传的 `upload_token`——经过数字签名的一组数据信息,该 `upload_token` 作为文件上传流中 `multipart/form-data` 的一部分进行传输。
Qiniu::RS.put_file :file => file_path,
:key => record_id,
:bucket => bucket_name,
:mime_type => file_mime_type,
:note => some_notes,
:enable_crc32_check => true
`Qiniu::RS.generate_upload_token` 函数原型如下:
Qiniu::RS.generate_upload_token :scope => target_bucket,
:expires_in => expires_in_seconds,
:callback_url => callback_url,
:callback_body_type => callback_body_type,
:customer => end_user_id,
:escape => allow_upload_callback_api
**参数**
:scope
: 必须,字符串类型(String),设定文件要上传到的目标 `bucket`
:expires_in
: 可选,数字类型,用于设置上传 URL 的有效期,单位:秒,缺省为 3600 秒,即 1 小时后该上传链接不再有效(但该上传URL在其生成之后的59分59秒都是可用的)。
:callback_url
: 可选,字符串类型(String),用于设置文件上传成功后,七牛云存储服务端要回调客户方的业务服务器地址。
:callback_body_type
: 可选,字符串类型(String),用于设置文件上传成功后,七牛云存储服务端向客户方的业务服务器发送回调请求的 `Content-Type`
:customer
: 可选,字符串类型(String),客户方终端用户(End User)的ID,该字段可以用来标示一个文件的属主,这在一些特殊场景下(比如给终端用户上传的图片打上名字水印)非常有用。
:escape
: 可选,数字类型,可选值 0 或者 1,缺省为 0 。值为 1 表示 callback 传递的自定义数据中允许存在转义符号 `$(VarExpression)`,参考 [VarExpression](/v3/api/words/#VarExpression)。
`escape` 的值为 `1` 时,常见的转义语法如下:
-`callbackBodyType``application/json` 时,一个典型的自定义回调数据([CallbackParams](/v3/api/io/#CallbackParams))为:
`{foo: "bar", w: $(imageInfo.width), h: $(imageInfo.height), exif: $(exif)}`
-`callbackBodyType``application/x-www-form-urlencoded` 时,一个典型的自定义回调数据([CallbackParams](/v3/api/io/#CallbackParams))为:
`foo=bar&w=$(imageInfo.width)&h=$(imageInfo.height)&exif=$(exif)`
**返回值**
返回一个字符串类型(String)的用于上传文件用的临时授权 `upload_token`
<a name="upload-server-side"></a>
#### 服务端上传文件
通过 `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),本地文件可被读取的有效路径
@@ -123,48 +191,89 @@ title: Ruby SDK 使用指南 | 七牛云存储
: 可选,字符串类型(String),文件的 mime-type 值。如若不传入,SDK 会自行计算得出,若计算失败缺省使用 application/octet-stream 代替之。
:note
: 可选,字符串类型(String),备注信息。
: 可选,字符串类型(String),为文件添加备注信息。
:callback_params
: 可选,String 或者 Hash 类型,文件上传成功后,七牛云存储向客户方业务服务器发送的回调参数。
:enable_crc32_check
: 可选,Boolean 类型,是否启用文件上传 crc32 校验,默认为 false 。
: 可选,Boolean 类型,是否启用文件上传 crc32 校验,缺省为 false 。
:rotate
: 可选,数字类型,上传图片时专用,可针对图片上传后进行旋转。该参数值为 0 :表示根据图像EXIF信息自动旋转;值为 1 : 右转90度;值为 2 :右转180度;值为 3 : 右转270度。
**返回值**
上传成功,返回 `true`,否则返回 `false`
上传成功,返回如下一个 Hash
**针对 NotFound 处理**
{"hash"=>"FgHk-_iqpnZji6PsNr4ghsK5qEwR"}
您可以上传一个应对 HTTP 404 出错处理的文件,当您 [创建公开外链](#publish) 后,若公开的外链找不到该文件,即可使用您上传的“自定义404文件”代替之。要这么做,您只须使用 `Qiniu::RS.put_file` 函数上传一个 `key` 为固定字符串类型的值 `errno-404` 即可
上传失败,会抛出 `UploadFailedError` 异常
<a name="resumable-upload"></a>
##### 断点续上传
无需任何额外改动,SDK 提供的 `Qiniu::RS.upload_file()` 方法缺省支持断点续上传。默认情况下,SDK 会自动启用断点续上传的方式来上传超过 4MB 大小的文件。您也可以在 [应用接入](/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-file-for-not-found"></a>
##### 针对 NotFound 场景处理
您可以上传一个应对 HTTP 404 出错处理的文件,当您 [创建公开外链](#publish) 后,若公开的外链找不到该文件,即可使用您上传的“自定义404文件”代替之。要这么做,您只须使用 `Qiniu::RS.upload_file` 函数上传一个 `key` 为固定字符串类型的值 `errno-404` 即可。
除了使用 SDK 提供的方法,同样也可以借助七牛云存储提供的命令行辅助工具 [qboxrsctl](https://github.com/qiniu/devtools/tags) 达到同样的目的:
qboxrsctl put <Bucket> <Key> <LocalFile>
将其中的 `<Key>` 换作 `errno-404` 即可。
注意,每个 `<Bucket>` 里边有且只有一个 `errno-404` 文件,上传多个,最后的那一个会覆盖前面所有的。
<a name="upload-client-side"></a>
#### 客户端上传流程
#### 客户端直传文件
<a name="put_auth"></a>
客户端上传流程和服务端上传类似,差别在于:客户端直传文件所需的 `upload_token` 可以选择在客户方的业务服务器端生成,也可以选择在客户方的客户端程序里边生成。选择前者,可以和客户方的业务揉合得更紧密和安全些,比如防伪造请求。
#### 获取用于上传文件的临时授权URL
简单来讲,客户端上传流程也分为两步:
Qiniu::RS.put_auth(expires_in = nil, callback_url = nil)
1. 获取 `upload_token`[用于上传文件的临时授权凭证](#generate-upload-token)
2. 将该 `upload_token` 作为文件上传流 `multipart/form-data` 中的一部分实现上传操作
要上传一个文件,首先需要调用 SDK 提供的 `Qiniu::RS.put_auth` 函数来获取一个经过授权用于临时匿名上传的 URL 。 “临时” 一词表示该 URL 有一定的时效性,即过一段时间后会过期,有效期由传入的参数 `expires_in` 决定,缺省情况下 `expires_in` 的值是 3600 秒,即 1 小时后该上传链接不再有效(但该上传URL在其生成之后的59分59秒都是可用的)
**参数**
expires_in
: 可选,整型,用于设置上传 URL 的有效期,单位:秒,缺省为 3600 秒
callback_url
: 可选,字符串类型(String),用于设置文件往这个 URL 上传成功后,七牛云存储服务端要回调客户方的业务服务器地址。
**返回值**
如果请求成功,返回一个字符串类型(String)的用于上传文件的已授权的临时有效 URL ,否则返回 `false`
**示例**
remote_upload_url = Qiniu::RS.put_auth(60, 'http://api.example.com/notifications/qiniu-rs')
如果您的网络程序是从云端(服务端程序)到终端(手持设备应用)的架构模型,且终端用户有使用您移动端App上传文件(比如照片或视频)的需求,可以把您服务器得到的此 `remote_upload_url` 返回给手持设备端的App,然后您的移动 App 可以使用 [七牛云存储 Objective-SDK iOS](http://docs.qiniutek.com/v2/sdk/objc/) 或 [七牛云存储 Java-SDKAndroid](http://docs.qiniutek.com/v2/sdk/java/) 的相关上传函数或参照 [七牛云存储API之文件上传](http://docs.qiniutek.com/v2/api/io/#rs-PutFile) 往该 `remote_upload_url` 上传文件。这样,您的终端用户即可把数据(比如图片或视频)直接上传到七牛云存储服务器上无须经由您的服务端中转,而且在上传之前,七牛云存储做了智能加速,终端用户上传数据始终是离他物理距离最近的存储节点。当终端用户上传成功后,七牛云存储服务端会向您指定的 `callback_url` 发送回调数据。在此示例程序中,七牛云存储服务端会将一组关于终端用户上传的数据的属性信息通过 HTTP POST 以 `application/x-www-form-urlencoded` 编码的方式发送到 `http://api.example.com/notifications/qiniu-rs` 这个地址,假设该地址是您业务服务器用于接收处理回调信息的地址。
如果您的网络程序是从云端(服务端程序)到终端(手持设备应用)的架构模型,且终端用户有使用您移动端App上传文件(比如照片或视频)的需求,可以把您服务器得到的此 `upload_token` 返回给手持设备端的App,然后您的移动 App 可以使用 [七牛云存储 Objective-SDK iOS](http://docs.qiniutek.com/v3/sdk/objc/) 或 [七牛云存储 Android-SDK](http://docs.qiniutek.com/v3/sdk/android/) 的相关上传函数或参照 [七牛云存储API之文件上传](http://docs.qiniutek.com/v3/api/io/#upload) 直传文件。这样,您的终端用户即可把数据(比如图片或视频)直接上传到七牛云存储服务器上无须经由您的服务端中转,而且在上传之前,七牛云存储做了智能加速,终端用户上传数据始终是离他物理距离最近的存储节点。当终端用户上传成功后,七牛云存储服务端会向您指定的 `callback_url` 发送回调数据。如果 `callback_url` 所在的服务处理完毕后输出 `JSON` 格式的数据,七牛云存储服务端会将该回调请求所得的响应信息原封不动地返回给终端应用程序
<a name="stat"></a>
@@ -288,7 +397,7 @@ key
<a name="drop"></a>
### 删除所有文件(单个“表”
### 删除所有文件(单个 bucket
Qiniu::RS.drop(bucket)
@@ -412,7 +521,7 @@ keys
调用 `Qiniu::RS.publish` 函数可以将您在七牛云存储中的资源表 `bucket` 发布到某个 `domain` 下,`domain` 需要在 DNS 管理里边 CNAME 到 `iovip.qbox.me`
这样,用户就可以通过 `http://<domain>/<key>` 来访问资源表 `bucket` 中的文件。键值为 `foo/bar/file` 的文件对应访问 URL 为 `http://<domain>/foo/bar/file`。 另外,`domain` 可以是一个真实的域名,比如 `www.example.com`,也可以是七牛云存储的二级路径,比如 `io.qbox.me/example`
这样,用户就可以通过 `http://<domain>/<key>` 来访问资源表 `bucket` 中的文件。键值为 `foo/bar/file` 的文件对应访问 URL 为 `http://<domain>/foo/bar/file`。 另外,`domain` 可以是一个真实的域名,比如 `www.example.com`,也可以是七牛云存储的二级路径,比如 `iovip.qbox.me/example`
例如:执行 `Qiniu::RS.publish("cdn.example.com", "EXAMPLE_BUCKET")` 后,那么键名为 `foo/bar/file` 的文件可以通过 `http://cdn.example.com/foo/bar/file` 访问。
@@ -445,6 +554,64 @@ domain
如果撤销成功,返回 `true`,否则返回 `false`
<a name="buckets"></a>
### Bucket(资源表)管理
<a name="mkbucket"></a>
#### 创建 Bucket
Qiniu::RS.mkbucket(bucket_name)
可以通过 SDK 提供的 `Qiniu::RS.mkbucket` 函数创建一个 bucket(资源表)。
**参数**
bucket_name
: 必须,字符串类型(String),资源表 bucket 的名称。
**返回值**
如果指定 bucket 创建成功,返回 `true`,否则返回 `false`
<a name="list-all-buckets"></a>
#### 列出所有 Bucket
Qiniu::RS.buckets
可以通过 SDK 提供的 `Qiniu::RS.buckets` 函数列出当前登录客户的所有 buckets(资源表)。
**返回值**
如果请求成功,返回一个 buckets 的列表(Array),否则返回 `false`
["Bucket1", "Bucket2", …, "BucketN"]
<a name="set-protected"></a>
#### 访问控制
Qiniu::RS.set_protected(bucket_name, protected_mode)
可以通过 SDK 提供的 `Qiniu::RS.set_protected` 函数来设置指定 bucket 的访问属性,一般在水印处理时作原图保护用。
**参数**
bucket_name
: 必须,字符串类型(String),指定资源表 bucket 的名称。
protected_mode
: 必须,整型,值为 1 或者 0,值为 1 表示启用保护模式,反之亦然。
该函数不常用,一般在特殊场景下会用到。比如给图片打水印时,首先要设置原图保护,禁用公开的图像处理操作,采用水印的特殊图像处理,而保护原图就可以通过该函数操作实现。
**返回值**
如果设置成功,返回 `true`,否则返回 `false`
<a name="op-image"></a>
### 图像处理
@@ -517,7 +684,7 @@ url
: 必须,字符串类型(String),图片的下载链接,需是 `Qiniu::RS.get`(或`Qiniu::RS.batch_get`)函数返回值中 `url` 字段的值,或者是 `Qiniu::RS.download`(或`Qiniu::RS.batch_download`)函数返回的下载链接。且文件本身必须是图片。
spec
: 可选,字符串或整型的枚举值,指定缩略图的具体规格,参考 [七牛云存储API之缩略图预览](/v2/api/foimg/#fo-imagePreview) 和 [自定义缩略图规格](/v2/api/foimg/#fo-imagePreviewEx) 。该值缺省为 0 (即输出宽800px高600px图片质量为85的缩略图)
: 可选,字符串或整型的枚举值,指定缩略图的具体规格,参考 [七牛云存储API之缩略图预览](/v3/api/foimg/#fo-imagePreview) 和 [自定义缩略图规格](/v3/api/foimg/#fo-imagePreviewEx) 。该值缺省为 0 (即输出宽800px高600px图片质量为85的缩略图)
**返回值**
@@ -553,7 +720,7 @@ mogrify_options
:auto_orient => <TrueOrFalse>
}
`Qiniu::RS.image_mogrify_preview_url()` 方法是对七牛云存储图像处理高级接口的完整包装,关于 `mogrify_options` 参数里边的具体含义和使用方式,可以参考文档:[图像处理高级接口](/v2/api/foimg/#fo-imageMogr)。
`Qiniu::RS.image_mogrify_preview_url()` 方法是对七牛云存储图像处理高级接口的完整包装,关于 `mogrify_options` 参数里边的具体含义和使用方式,可以参考文档:[图像处理高级接口](/v3/api/foimg/#fo-imageMogr)。
**返回值**
@@ -594,7 +761,7 @@ mogrify_options
:auto_orient => <TrueOrFalse>
}
`Qiniu::RS::Image.mogrify_preview_url()` 方法是对七牛云存储图像处理高级接口的完整包装,关于 `mogrify_options` 参数里边的具体含义和使用方式,可以参考文档:[图像处理高级接口](/v2/api/foimg/#fo-imageMogr)。
`Qiniu::RS::Image.mogrify_preview_url()` 方法是对七牛云存储图像处理高级接口的完整包装,关于 `mogrify_options` 参数里边的具体含义和使用方式,可以参考文档:[图像处理高级接口](/v3/api/foimg/#fo-imageMogr)。
**返回值**
@@ -633,6 +800,229 @@ mogrify_options
end
<a name="image-watermarking"></a>
## 高级图像处理(水印)
<a name="watermarking-pre-work"></a>
### 水印准备工作
为了保护用户原图和方便用户访问打过水印之后的图片,在经水印作用之前,需进行以下一些设置:
1. [设置原图保护](#watermarking-set-protected)
2. [设置水印预览图URL分隔符](#watermarking-set-sep)
3. [设置水印预览图规格别名](#watermarking-set-style)
<a name="watermarking-set-protected"></a>
#### 1. 设置原图保护
用户的图片打上水印后,其原图不可见。通过给原图所在的 Bucket(资源表)设置访问控制,可以达到保护原图的目的,详情请参考 [Bucket(资源表)管理之访问控制](set-protected)。
设置原图保护也可以借助七牛云存储提供的命令行辅助工具 [qboxrsctl](https://github.com/qiniu/devtools/tags) 来实现:
// 为<Bucket>下面的所有图片设置原图保护
qboxrsctl protected <Bucket> <Protected>
<a name="watermarking-set-sep"></a>
#### 2. 设置水印预览图URL分隔符
没有设置水印前,用户可以通过如下公开链接的形式访问原图([创建公开外链后的情况下](/v3/api/io/#rs-Publish)):
http://<Domain>/<Key>
设置水印后,其原图属性为私有,不能再通过这种形式访问。但是用户可以在原图的 `<Key>` 后面加上“分隔符”,以及相应的水印风格样式来访问打水印后的图片。例如,假设您为用户设定的访问水印图的分隔符为中划线 “-”,那么用户可以通过这种形式来访问打水印后的图片:
http://<Domain>/<Key>-/imageView/<Mode>/w/<Width>/h/<Height>/q/<Quality>/format/<Format>/sharpen/<Sharpen>/watermark/<HasWatermark>
其中,`HasWatermark` 参数为 `0` (或者没有)表示不打水印,为 `1` 表示给图片打水印。
通过 SDK 提供的 `Qiniu::RS.set_separator` 函数可以设置水印预览图URL分隔符:
Qiniu::RS.set_separator(bucket_name, separator)
**参数**
bucket_name
: 必须,字符串类型(String),图片所在的 Bucket(资源表) 名称
separator
: 必须,字符串类型(String),源图片与预览图规格之间的分割符
**返回值**
操作成功返回 `true`,否则返回 `false`
除了使用 SDK 提供的方法,同样可以借助七牛云存储提供的命令行辅助工具 [qboxrsctl](https://github.com/qiniu/devtools/tags) 达到同样的目的:
// 设置预览图分隔符
qboxrsctl separator <Bucket> <Sep>
<a name="watermarking-set-style"></a>
#### 3. 设置水印预览图规格别名
通过步骤2中所描述的水印预览图 URL 来访问打水印后的图片毕竟较为繁琐,因此可以通过为该水印预览图规格设置“别名”的形式来访问。如:
别名(Name | 规格(Style | 说明
----------- | ------------ | -------
small.jpg | imageView/0/w/120/h/90 | 大小为 120x90,不打水印
middle.jpg | imageView/0/w/440/h/330/watermark/1 | 大小为 440x330,打水印
large.jpg | imageView/0/w/1280/h/760/watermark/1 | 大小为 1280x760,打水印
SDK 提供了 `Qiniu::RS.set_style` 函数可以定义预览图规格别名,该函数原型如下:
Qiniu::RS.set_style(bucket, name, style)
**参数**
bucket
: 必须,字符串类型(String),图片所在的 Bucket(资源表) 名称
name
: 必须,字符串类型(String),预览图规格名称(别名)
style
: 必须,字符串类型(String),具体的规格样式
**返回值**
操作成功返回 `true`,否则返回 `false`
除了使用 SDK 提供的方法,同样也可以借助七牛云存储提供的命令行辅助工具 [qboxrsctl](https://github.com/qiniu/devtools/tags) 达到同样的目的:
// 为 <Buecket> 下面的所有图片设置名为 <Name> 的 <Style>
qboxrsctl style <Bucket> <Name> <Style>
无论是通过 SDK 提供的方法还是命令行辅助工具操作,在设置完成后,即可通过通过以下方式来访问设定规格后的图片:
// 其中 “-” 为分隔符,“small.jpg” 为预览图规格别名
[GET] http://<Domain>/<Key>-small.jpg
// 其中 “!” 为分隔符,“middle.jpg” 为预览图规格别名
[GET] http://<Domain>/<Key>!middle.jpg
// 其中 “@” 为分隔符,“large.jpg” 为预览图规格别名
[GET] http://<Domain>/<Key>@large.jpg
以上这些设置水印模板前的准备只需操作一次,即可对后续设置的所有水印模板生效。由于是一次性操作,建议使用 qboxrsctl 命令行辅助工具进行相关设置。
**取消水印预览图规格设置**
您也可以为某个水印预览图规格取消“别名”设置,SDK 提供了相应的方法:
Qiniu::RS.unset_style(bucket, name)
**参数**
bucket
: 必须,字符串类型(String),图片所在的 Bucket(资源表) 名称
name
: 必须,字符串类型(String),预览图规格名称(别名)
**返回值**
操作成功返回 `true`,否则返回 `false`
除了使用 SDK 提供的方法,同样也可以借助七牛云存储提供的命令行辅助工具 [qboxrsctl](https://github.com/qiniu/devtools/tags) 达到同样的目的:
// 取消预览图规格别名为 <Name> 的 Style
qboxrsctl unstyle <Bucket> <Name>
<a name="watermarking-set-template"></a>
### 设置水印模板
给图片加水印,SDK 提供了设置水印模板的函数:`Qiniu::RS.set_watermark` ,通过该函数操作,客户方可以设置通用的水印模板,也可以为客户方的每一个终端用户分别设置一个水印模板。
`Qiniu::RS.set_watermark` 函数原型如下:
Qiniu::RS.set_watermark(customer_id, {
:font => <FontName>,
:fontsize => <FontSize>,
:fill => <FillColor>,
:text => <WatermarkText>,
:bucket => <LogoBucket>,
:dissolve => <Dissolve>,
:gravity => <Gravity>,
:dx => <DistanceX>,
:dy => <DistanceY>
})
**参数**
1. `customer_id = <EndUserID>`
: 客户方终端用户标识。如果`customer_id``nil`,则表示设置默认水印模板。作为面向终端用户的服务提供商,您可以为不同的用户设置不同的水印模板,只需在设置水印模板的时候传入`customer_id`参数。如果该参数未设置,则表示为终端用户设置一个默认模板。举例:假如您为终端用户提供的是一个手机拍照软件,用户拍照后图片存储于七牛云存储服务器。为了给每个用户所上传的图片打上标有该用户用户名的水印,您可以为该用户设置一个水印模板,其水印文字可以是该终端用户的用户名。但如果您未给该终端用户设置模板,那么水印上的所有设置都是默认的(其文字部分可能是你们自己设置的企业标识)。该 `customer_id` 和 [Qiniu::RS.generate_upload_token](#generate-upload-token) 中的 `customer` 参数含义一致,结合这点,您很容易想明白为什么 `Qiniu::RS.generate_upload_token` 函数中会有 `customer` 这个可选参数还有 `Qiniu::RS.set_watermark` 函数中会有 `customer_id` 参考以及两者间的关系。
2. `:font => <FontName>`
: 为水印上的文字设置一个默认的字体名,可选。
3. `:fontsize => <FontSize>`
: 字体大小,可选,0表示默认,单位: 缇,等于 1/20 磅。
4. `:fill => <FillColor>`
: 字体颜色,可选。
5. `:text => <WatermarkText>`
: 水印文字,必须,图片用 \0 - \9 占位。
6. `:bucket => <ImageFromBucket>`
: 如果水印中有图片,需要指定图片所在的 `RS Bucket` 名称,可选。
7. `:dissolve => <Dissolve>`
: 透明度,可选,字符串,如50%。
8. `:gravity => <Gravity>`
: 位置,可选,字符串,默认为右下角(SouthEast)。可选的值包括:NorthWest、North、NorthEast、West、Center、East、SouthWest、South和SouthEast。
9. `:dx => <DistanceX>`
: 横向边距,可选,默认值为10,单位px。
10. `:dy => <DistanceY>`
: 纵向边距,可选,默认值为10,单位px。
**返回值**
操作成功返回 `true`,否则返回 `false`
<a name="watermarking-get-template"></a>
### 获取水印模板
SDK 提供了 `Qiniu::RS.get_watermark` 函数获取指定终端用户或者缺省的水印模板。该函数原型如下:
Qiniu::RS.get_watermark(customer_id = nil)
**参数**
customer_id
: 客户方终端用户标识,可选,字符串类型,含义同 [Qiniu::RS.set_watermark](#watermarking-set-template) 函数中的 `customer_id` 参数。该值缺省为 `nil`,如果该值为 `nil`,则表示取默认的通用水印模板。
**返回值**
如果请求成功,返回如下一段 Hash 结构的数据;否则返回 `false`
{
font: <FontName>
fontsize: <FontSize>
fill: <FillColor>
text: <WatermarkText>
bucket: <LogoBucket>
dissolve: <Dissolve>
gravity: <Gravity>
dx: <DistanceX>
dy: <DistanceY>
}
请求成功后返回数据的含义同 [设置水印模板](#watermarking-set-template) 时传入的参数一致。
<a name="Contributing"></a>
## 贡献代码
+80 -7
View File
@@ -1,20 +1,23 @@
# -*- encoding: utf-8 -*-
require 'qiniu/rs/version'
module Qiniu
module RS
autoload :Version, 'qiniu/rs/version'
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 :UP, 'qiniu/rs/up'
autoload :RS, 'qiniu/rs/rs'
autoload :EU, 'qiniu/rs/eu'
autoload :Pub, 'qiniu/rs/pub'
autoload :Image, 'qiniu/rs/image'
autoload :AccessToken, 'qiniu/tokens/access_token'
autoload :QboxToken, 'qiniu/tokens/qbox_token'
autoload :UploadToken, 'qiniu/tokens/upload_token'
autoload :Abstract, 'qiniu/rs/abstract'
class << self
@@ -29,6 +32,46 @@ module Qiniu
code == StatusOK
end
def mkbucket(bucket_name)
code, data = RS.mkbucket(bucket_name)
code == StatusOK
end
def buckets
code, data = RS.buckets
code == StatusOK ? data : false
end
def set_protected(bucket, protected_mode)
code, data = Pub.set_protected(bucket, protected_mode)
code == StatusOK
end
def set_separator(bucket, separator)
code, data = Pub.set_separator(bucket, separator)
code == StatusOK
end
def set_style(bucket, name, style)
code, data = Pub.set_style(bucket, name, style)
code == StatusOK
end
def unset_style(bucket, name)
code, data = Pub.unset_style(bucket, name)
code == StatusOK
end
def set_watermark(customer_id, options = {})
code, data = EU.set_watermark(customer_id, options)
code == StatusOK
end
def get_watermark(customer_id = nil)
code, data = EU.get_watermark(customer_id)
code == StatusOK ? data : false
end
def put_auth(expires_in = nil, callback_url = nil)
code, data = IO.put_auth(expires_in, callback_url)
code == StatusOK ? data["url"] : false
@@ -56,6 +99,38 @@ module Qiniu
code == StatusOK
end
def upload_file opts = {}
[:uptoken, :file, :bucket, :key].each do |opt|
raise MissingArgsError, [opt] unless opts.has_key?(opt)
end
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 = UP.upload_with_token(opts[:uptoken],
opts[:file],
opts[:bucket],
opts[:key],
opts[:mime_type],
opts[:note],
opts[:customer],
opts[:callback_params],
opts[:rotate])
else
code, data = IO.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 = RS.stat(bucket, key)
code == StatusOK ? data : false
@@ -142,10 +217,6 @@ module Qiniu
code == StatusOK ? data : false
end
#def generate_upload_token(scope, expires_in, callback_url = nil, return_url = nil)
# Utils.generate_upload_token(scope, expires_in, callback_url, return_url)
#end
def generate_upload_token(opts = {})
token_obj = UploadToken.new(opts)
token_obj.access_key = Config.settings[:access_key]
@@ -153,7 +224,9 @@ module Qiniu
#token_obj.scope = opts[:scope]
#token_obj.expires_in = opts[:expires_in]
#token_obj.callback_url = opts[:callback_url]
#token_obj.return_url = opts[:return_url]
#token_obj.callback_body_type = opts[:callback_body_type]
#token_obj.customer = opts[:customer]
#token_obj.escape = opts[:escape]
token_obj.generate_token
end
+24
View File
@@ -0,0 +1,24 @@
# -*- encoding: utf-8 -*-
module Qiniu
module RS
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
end
end
+10 -4
View File
@@ -18,7 +18,7 @@ module Qiniu
:password => password
}
code, data = http_request Config.settings[:auth_url], post_data
reset_token(data["access_token"], data["refresh_token"]) if code == 200
reset_token(data["access_token"], data["refresh_token"]) if Utils.is_response_ok?(code)
[code, data]
end
@@ -29,7 +29,7 @@ module Qiniu
: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
reset_token(data["access_token"], data["refresh_token"]) if Utils.is_response_ok?(code)
[code, data]
end
@@ -48,7 +48,7 @@ module Qiniu
raise MissingUsernameOrPassword if (@username.nil? || @password.nil?)
code, data = exchange_by_password!(@username, @password)
end
if code == 200
if Utils.is_response_ok?(code)
retry_times += 1
if Config.settings[:auto_reconnect] && retry_times < Config.settings[:max_retry_times]
return call_with_logged_in(url, data, retry_times)
@@ -70,7 +70,13 @@ module Qiniu
else
code, data = Auth.call_with_signature(url, data, 0, options)
end
rescue [MissingAccessToken, MissingRefreshToken, MissingUsernameOrPassword] => e
rescue MissingAccessToken => e
Log.logger.error e
code, data = 401, {}
rescue MissingRefreshToken => e
Log.logger.error e
code, data = 401, {}
rescue MissingUsernameOrPassword => e
Log.logger.error e
code, data = 401, {}
end
+12 -5
View File
@@ -8,7 +8,7 @@
# Qbox::Config.load "path/to/your_project/config/qiniu.yml"
#
require "qiniu/rs/version"
require 'tmpdir'
module Qiniu
module RS
@@ -16,21 +16,28 @@ module Qiniu
class << self
DEFAULT_OPTIONS = {
:user_agent => 'Qiniu-RS-Ruby-SDK-' + VERSION + '()',
:user_agent => 'Qiniu-RS-Ruby-SDK-' + Version.to_s + '()',
: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://rs.qbox.me",
:io_host => "http://iovip.qbox.me",
:up_host => "http://up.qbox.me",
:pub_host => "http://pu.qbox.me:10200",
:eu_host => "http://eu.qbox.me",
:client_id => "a75604760c4da4caaa456c0c5895c061c3065c5a",
:client_secret => "75df554a39f58accb7eb293b550fa59618674b7d",
: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 + 'Qiniu-RS-Ruby-SDK'
}
REQUIRED_OPTION_KEYS = [:client_id, :client_secret, :auth_url, :rs_host, :io_host]
REQUIRED_OPTION_KEYS = [:access_key, :secret_key]
attr_reader :settings, :default_params
+22
View File
@@ -0,0 +1,22 @@
# -*- encoding: utf-8 -*-
module Qiniu
module RS
module EU
class << self
include Utils
def set_watermark(customer_id, options = {})
Auth.request Config.settings[:eu_host] + '/wmset', options.merge({:customer => customer_id})
end
def get_watermark(customer_id = nil)
post_data = customer_id.nil? ? nil : {:customer => customer_id}
Auth.request Config.settings[:eu_host] + '/wmget', post_data
end
end
end
end
end
+38 -4
View File
@@ -4,9 +4,6 @@ module Qiniu
module RS
class Exception < RuntimeError
def to_s
inspect
end
end
class ResponseError < Exception
@@ -32,7 +29,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 +37,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 ')
+10 -1
View File
@@ -34,8 +34,16 @@ module Qiniu
Auth.request url, ::IO.read(local_file), options
end
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)
callback_params = {:bucket => bucket, :key => key, :mime_type => mime_type} if callback_params.nil?
callback_query_string = Utils.generate_query_string(callback_params)
url = Config.settings[:up_host] + '/upload'
Utils.upload_multipart_data(url, local_file, action_params, callback_query_string, uptoken)
end
private
def _generate_action_params(local_file, bucket, key = nil, mime_type = nil, custom_meta = nil, enable_crc32_check = false)
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)
key = Digest::SHA1.hexdigest(local_file + Time.now.to_s) if key.nil?
entry_uri = bucket + ':' + key
@@ -46,6 +54,7 @@ module Qiniu
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
+37
View File
@@ -0,0 +1,37 @@
# -*- encoding: utf-8 -*-
module Qiniu
module RS
module Pub
class << self
include Utils
def set_protected(bucket, protected_mode)
host = Config.settings[:pub_host]
Auth.request %Q(#{host}/accessMode/#{bucket}/mode/#{protected_mode})
end
def set_separator(bucket, separator)
host = Config.settings[:pub_host]
encoded_separator = Utils.urlsafe_base64_encode(separator)
Auth.request %Q(#{host}/separator/#{bucket}/sep/#{encoded_separator})
end
def set_style(bucket, name, style)
host = Config.settings[:pub_host]
encoded_name = Utils.urlsafe_base64_encode(name)
encoded_style = Utils.urlsafe_base64_encode(style)
Auth.request %Q(#{host}/style/#{bucket}/name/#{encoded_name}/style/#{encoded_style})
end
def unset_style(bucket, name)
host = Config.settings[:pub_host]
encoded_name = Utils.urlsafe_base64_encode(name)
Auth.request %Q(#{host}/unstyle/#{bucket}/name/#{encoded_name})
end
end
end
end
end
+8
View File
@@ -6,6 +6,14 @@ module Qiniu
class << self
include Utils
def buckets
Auth.request Config.settings[:rs_host] + '/buckets'
end
def mkbucket(bucket_name)
Auth.request Config.settings[:rs_host] + '/mkbucket/' + bucket_name
end
def stat(bucket, key)
Auth.request Config.settings[:rs_host] + '/stat/' + encode_entry_uri(bucket, key)
end
+328
View File
@@ -0,0 +1,328 @@
# -*- encoding: utf-8 -*-
require 'zlib'
require 'yaml'
require 'tmpdir'
require 'fileutils'
require 'mime/types'
require 'digest/sha1'
require 'qiniu/rs/abstract'
require 'qiniu/rs/exceptions'
require 'qiniu/rs/io'
module Qiniu
module RS
module UP
PROGRESS_TMP_FILE = 'progresses'
CHECKSUM_TMP_FILE = 'ctxes'
module AbstractClass
class ChunkProgressNotifier
include Qiniu::RS::Abstract
abstract_methods :notify
# def notify(block_index, block_put_progress); end
end
class BlockProgressNotifier
include Qiniu::RS::Abstract
abstract_methods :notify
# def notify(block_index, checksum); end
end
end
class ChunkProgressNotifier < AbstractClass::ChunkProgressNotifier
attr_reader :tmpdata
def initialize(id)
@tmpdata = UP::TmpData.new(id, PROGRESS_TMP_FILE)
end
def notify(index, progress)
@tmpdata.set(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 BlockProgressNotifier < AbstractClass::BlockProgressNotifier
attr_reader :tmpdata
def initialize(id)
@tmpdata = UP::TmpData.new(id, CHECKSUM_TMP_FILE)
end
def notify(index, checksum)
@tmpdata.set(index, checksum)
Utils.debug "block #{index}: {ctx: #{checksum}} successfully uploaded."
Utils.debug "block #{index}: {checksum: #{checksum}} successfully uploaded."
end
end
class TmpData
def initialize(dir, filename)
@tmpdir = Config.settings[:tmpdir] + File::SEPARATOR + dir
FileUtils.mkdir_p(@tmpdir) unless Dir.exists?(@tmpdir)
@tmpfile = @tmpdir + File::SEPARATOR + filename
end
def init(values)
File.open(@tmpfile, "w") do |f|
YAML::dump(values, f)
Utils.debug %Q(Initializing tmpfile: #{@tmpfile})
end
end
def all
File.exist?(@tmpfile) ? YAML.load_file(@tmpfile) : []
end
def set(index, value)
values = all
values[index] = value
File.open(@tmpfile, "w") do |f|
YAML::dump(values, f)
Utils.debug %Q(Updating tmpfile: #{@tmpfile})
end
end
def sweep!
FileUtils.rm_r(@tmpdir) if Dir.exists?(@tmpdir)
end
end
class << self
include Utils
def upload_with_token(uptoken,
local_file,
bucket,
key = nil,
mime_type = nil,
custom_meta = nil,
customer = nil,
callback_params = nil,
rotate = nil)
raise NoSuchFileError, local_file unless File.exist?(local_file)
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
if fsize > Config.settings[:block_size]
code, data = _resumable_upload(uptoken, fh, fsize, bucket, key, mime_type, custom_meta, customer, callback_params, rotate)
else
code, data = IO.upload_with_token(uptoken, local_file, bucket, key, mime_type, custom_meta, callback_params, true, rotate)
end
[code, data]
ensure
ifile.close unless ifile.nil?
end
end
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
def _new_block_put_progress_data
{:ctx => nil, :offset => 0, :restsize => nil, :status_code => nil, :host => nil}
end
def _call_binary_with_token(uptoken, url, data, content_type = nil, retry_times = 0)
options = {
:method => :post,
:content_type => 'application/octet-stream',
:upload_signature_token => uptoken
}
options[:content_type] = content_type if !content_type.nil? && !content_type.empty?
code, data = http_request url, data, options
unless Utils.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
[code, data]
end
def _mkblock(uptoken, block_size, body)
url = Config.settings[:up_host] + "/mkblk/#{block_size}"
_call_binary_with_token(uptoken, url, body)
end
def _putblock(uphost, uptoken, ctx, offset, body)
url = uphost + "/bput/#{ctx}/#{offset}"
_call_binary_with_token(uptoken, url, body)
end
def _resumable_put_block(uptoken, fh, block_index, block_size, chunk_size, progress, retry_times = 1, 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 = _mkblock(uptoken, block_size, body)
body_crc32 = Zlib.crc32(body)
if Utils.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"]})
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 = _putblock(progress[:host], uptoken, progress[:ctx], progress[:offset], body)
body_crc32 = Zlib.crc32(body)
if Utils.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"]})
end
end
end
# return
return [code, data]
end
def _block_count(fsize)
((fsize + Config.settings[:block_size] - 1) / Config.settings[:block_size]).to_i
end
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)
if Utils.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
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 = Utils.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
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(key)
block_notifier = BlockProgressNotifier.new(key)
progresses = chunk_notifier.tmpdata.all
if progresses.empty?
block_count.times{progresses << _new_block_put_progress_data}
chunk_notifier.tmpdata.init(progresses)
end
checksums = block_notifier.tmpdata.all
if checksums.empty?
block_count.times{checksums << ''}
block_notifier.tmpdata.init(checksums)
end
code, data = _resumable_put(uptoken, fh, checksums, progresses, block_notifier, chunk_notifier)
if Utils.is_response_ok?(code)
uphost = data["host"]
entry_uri = bucket + ':' + key
code, data = _mkfile(uphost, uptoken, entry_uri, fsize, checksums, mime_type, custom_meta, customer, callback_params, rotate)
end
if Utils.is_response_ok?(code)
Utils.debug "File #{fh.path} {size: #{fsize}} successfully uploaded."
chunk_notifier.tmpdata.sweep!
block_notifier.tmpdata.sweep!
end
[code, data]
end
end
end
end
end
+26 -25
View File
@@ -1,6 +1,7 @@
# -*- encoding: utf-8 -*-
require 'uri'
require 'cgi'
require 'json'
require 'zlib'
require 'base64'
@@ -31,6 +32,20 @@ module Qiniu
{}
end
def is_response_ok?(status_code)
status_code/100 == 2
end
def response_error(status_code, errmsg)
[status_code, {"error" => errmsg}]
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]
@@ -41,8 +56,8 @@ module Qiniu
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[: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
@@ -55,8 +70,8 @@ module Qiniu
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)
unless is_response_ok?(code)
raise RequestFailed.new("Request Failed", response)
else
data = {}
body = response.respond_to?(:body) ? response.body : {}
@@ -91,20 +106,21 @@ module Qiniu
end
end
def upload_multipart_data(url, filepath, action_string, callback_query_string = '')
def upload_multipart_data(url, filepath, action_string, callback_query_string = '', uptoken = nil)
post_data = {
:params => callback_query_string,
:action => action_string,
:file => File.new(filepath, 'rb'),
:multipart => true
}
post_data[:auth] = uptoken unless uptoken.nil?
http_request url, post_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("&"))
total_param = params.map { |key, value| %Q(#{CGI.escape(key.to_s)}=#{CGI.escape(value.to_s).gsub('+', '%20')}) }
total_param.join("&")
end
def crc32checksum(filepath)
@@ -118,10 +134,10 @@ module Qiniu
signature = uri.path
query_string = uri.query
signature += '?' + query_string if !query_string.nil? && !query_string.empty?
signature += "\n";
signature += "\n"
if params.is_a?(Hash)
total_param = params.map { |key, value| key.to_s+"="+value.to_s }
signature += total_param.join("&")
params_string = generate_query_string(params)
signature += params_string
end
hmac = HMAC::SHA1.new(secret_key)
hmac.update(signature)
@@ -129,21 +145,6 @@ module Qiniu
%Q(#{access_key}:#{encoded_digest})
end
=begin
def generate_upload_token(scope, expires_in, callback_url = nil, return_url = nil)
access_key = Config.settings[:access_key]
secret_key = Config.settings[:secret_key]
params = {:scope => scope, :deadline => Time.now.to_i + expires_in}
params[:callbackUrl] = callback_url if !callback_url.nil? && !calback_url.empty?
params[:returnUrl] = return_url if !return_url.nil? && !return_url.empty?
signature = urlsafe_base64_encode(params.to_json)
hmac = HMAC::SHA1.new(secret_key)
hmac.update(signature)
encoded_digest = urlsafe_base64_encode(hmac.digest)
%Q(#{access_key}:#{encoded_digest}:#{signature})
end
=end
end
end
end
+13 -1
View File
@@ -2,6 +2,18 @@
module Qiniu
module RS
VERSION = "2.3.3"
module Version
MAJOR = 3
MINOR = 2
PATCH = 2
# 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
end
end
+2 -1
View File
@@ -1,5 +1,6 @@
# -*- encoding: utf-8 -*-
require 'cgi'
require 'json'
require 'qiniu/tokens/access_token'
@@ -21,7 +22,7 @@ module Qiniu
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 }
total_param = @params.map { |key, value| %Q(#{CGI.escape(key.to_s)}=#{CGI.escape(value.to_s).gsub('+', '%20')}) }
signature += total_param.join("&")
end
signature
+9 -5
View File
@@ -10,19 +10,23 @@ module Qiniu
include Utils
attr_accessor :scope, :expires_in, :callback_url, :return_url
attr_accessor :scope, :expires_in, :callback_url, :callback_body_type, :customer, :escape
def initialize(opts = {})
@scope = opts[:scope]
@expires_in = opts[:expires_in]
@expires_in = opts[:expires_in] || 3600
@callback_url = opts[:callback_url]
@return_url = opts[:return_url]
@callback_body_type = opts[:callback_body_type]
@customer = opts[:customer]
@escape = opts[:escape]
end
def generate_signature
params = {:scope => @scope, :deadline => Time.now.to_i + @expires_in}
params[:callbackUrl] = @callback_url if !@callback_url.nil? && !@calback_url.empty?
params[:returnUrl] = @return_url if !@return_url.nil? && !@return_url.empty?
params[:callbackUrl] = @callback_url if !@callback_url.nil? && !@callback_url.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
urlsafe_base64_encode(params.to_json)
end
+9 -9
View File
@@ -5,7 +5,7 @@ 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.description = %q{Qiniu Resource (Cloud) Storage SDK for Ruby. See: http://docs.qiniutek.com/v3/sdk/ruby/}
gem.summary = %q{Qiniu Resource (Cloud) Storage SDK for Ruby}
gem.homepage = "https://github.com/qiniu/ruby-sdk"
@@ -14,15 +14,15 @@ Gem::Specification.new do |gem|
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "qiniu-rs"
gem.require_paths = ["lib"]
gem.version = Qiniu::RS::VERSION
gem.version = Qiniu::RS::Version.to_s
# 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_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.7"
gem.add_runtime_dependency "rest-client", "~> 1.6"
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"
gem.add_runtime_dependency "ruby-hmac", "~> 0.4"
gem.add_runtime_dependency "jruby-openssl", "~> 0.7" if RUBY_PLATFORM == "java"
end
+30
View File
@@ -0,0 +1,30 @@
# -*- encoding: utf-8 -*-
require 'spec_helper'
require 'qiniu/rs/abstract'
describe Qiniu::RS::Abstract do
before(:each) do
@klass = Class.new do
include Qiniu::RS::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
+2 -2
View File
@@ -8,8 +8,8 @@ module Qiniu
describe Auth do
before :all do
@username = "test@qbox.net"
@password = "test"
@username = "qboxtest"
@password = "qboxtest123"
code, data = Qiniu::RS::Auth.exchange_by_password!(@username, @password)
code.should == 200
+65
View File
@@ -0,0 +1,65 @@
# -*- encoding: utf-8 -*-
require 'spec_helper'
require 'qiniu/rs'
require 'qiniu/rs/pub'
require 'qiniu/rs/eu'
module Qiniu
module RS
describe EU do
before :all do
@customer_id = "awhy.xu@gmail.com"
@bucket = "wm_test_bucket"
@key = "image_logo_for_test.png"
result = Qiniu::RS.mkbucket(@bucket)
puts result.inspect
result.should be_true
local_file = File.expand_path('../' + @key, __FILE__)
upopts = {:scope => @bucket, :expires_in => 3600, :customer => @customer_id}
uptoken = Qiniu::RS.generate_upload_token(upopts)
data = Qiniu::RS.upload_file :uptoken => uptoken, :file => local_file, :bucket => @bucket, :key => @key
puts data.inspect
code2, data2 = Qiniu::RS::Pub.set_separator(@bucket, "-")
code2.should == 200
puts data2.inspect
code3, data3 = Qiniu::RS::Pub.set_style(@bucket, "small.jpg", "imageView/1/w/120/h/120/q/85/format/jpg/watermark/1")
code3.should == 200
puts data3.inspect
end
after :all do
@bucket = "wm_test_bucket"
result = Qiniu::RS.drop(@bucket)
puts result.inspect
result.should_not be_false
end
context ".set_watermark" do
it "should works" do
options = {
:text => "Powered by QiniuRS"
}
code, data = Qiniu::RS::EU.set_watermark(@customer_id, options)
code.should == 200
puts data.inspect
end
end
context ".get_watermark" do
it "should works" do
code, data = Qiniu::RS::EU.get_watermark(@customer_id)
code.should == 200
puts data.inspect
end
end
end
end
end
+14 -22
View File
@@ -10,35 +10,20 @@ module Qiniu
describe Image 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
@bucket = "test_images_12345"
@key = "image_logo_for_test.png"
local_file = File.expand_path('../' + @key, __FILE__)
result = Qiniu::RS.drop(@bucket)
result.should_not be_false
result = Qiniu::RS.mkbucket(@bucket)
puts result.inspect
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
local_file = File.expand_path('../' + @key, __FILE__)
upopts = {:scope => @bucket, :expires_in => 3600, :customer => "awhy.xu@gmail.com"}
uptoken = Qiniu::RS.generate_upload_token(upopts)
data = Qiniu::RS.upload_file :uptoken => uptoken, :file => local_file, :bucket => @bucket, :key => @key
puts data.inspect
result = Qiniu::RS.get(@bucket, @key)
result["url"].should_not be_empty
@@ -56,6 +41,13 @@ module Qiniu
}
end
after :all do
@bucket = "test_images_12345"
result = Qiniu::RS.drop(@bucket)
puts result.inspect
result.should_not be_false
end
context ".info" do
it "should works" do
code, data = Qiniu::RS::Image.info(@source_image_url)
+23 -11
View File
@@ -1,4 +1,4 @@
# -*- encoding: utf-8 -*-
# Utils.-*- encoding: utf-8 -*-
require 'spec_helper'
require 'qiniu/rs/auth'
@@ -10,17 +10,19 @@ module Qiniu
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
@bucket = "test"
@bucket = "io_test_bucket"
@key = Digest::SHA1.hexdigest (Time.now.to_i+rand(100)).to_s
result = Qiniu::RS.mkbucket(@bucket)
puts result.inspect
result.should be_true
end
after :all do
@bucket = "io_test_bucket"
result = Qiniu::RS.drop(@bucket)
puts result.inspect
result.should_not be_false
end
context ".upload_file" do
@@ -44,6 +46,16 @@ module Qiniu
end
end
context ".upload_with_token" do
it "should works" do
upopts = {:scope => @bucket, :expires_in => 3600, :customer => "awhy.xu@gmail.com"}
uptoken = Qiniu::RS.generate_upload_token(upopts)
code, data = Qiniu::RS::IO.upload_with_token(uptoken, __FILE__, @bucket, @key, nil, nil, nil, true)
code.should == 200
puts data.inspect
end
end
end
end
end
+60
View File
@@ -0,0 +1,60 @@
# -*- encoding: utf-8 -*-
require 'spec_helper'
require 'qiniu/rs/auth'
require 'qiniu/rs/rs'
require 'qiniu/rs/pub'
module Qiniu
module RS
describe Pub do
before :all do
@bucket = "pub_test_bucket"
result = Qiniu::RS.mkbucket(@bucket)
puts result.inspect
result.should_not be_false
end
after :all do
@bucket = "pub_test_bucket"
result = Qiniu::RS.drop(@bucket)
puts result.inspect
result.should_not be_false
end
context ".set_protected" do
it "should works" do
code, data = Qiniu::RS::Pub.set_protected(@bucket, 1)
code.should == 200
puts data.inspect
end
end
context ".set_separator" do
it "should works" do
code, data = Qiniu::RS::Pub.set_separator(@bucket, "-")
code.should == 200
puts data.inspect
end
end
context ".set_style" do
it "should works" do
code, data = Qiniu::RS::Pub.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::RS::Pub.unset_style(@bucket, "small.jpg")
code.should == 200
puts data.inspect
end
end
end
end
end
+29 -20
View File
@@ -11,31 +11,40 @@ module Qiniu
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"
@bucket = "rs_test_bucket"
@key = Digest::SHA1.hexdigest (Time.now.to_i+rand(100)).to_s
@domain = 'cdn.example.com'
@domain = 'rs-test-bucket.dn.qbox.me'
code, data = Qiniu::RS::RS.mkbucket(@bucket)
puts [code, data].inspect
code.should == 200
end
after :all do
@bucket = "rs_test_bucket"
code, data = Qiniu::RS::RS.drop(@bucket)
puts [code, data].inspect
code.should == 200
end
context "IO.upload_file" do
it "should works" do
code, data = Qiniu::RS::IO.upload_file(@put_url, __FILE__, @bucket, @key)
code, data = Qiniu::RS::IO.put_auth()
puts data.inspect
code.should == 200
data["url"].should_not be_empty
data["expiresIn"].should_not be_zero
@put_url = data["url"]
code2, data2 = Qiniu::RS::IO.upload_file(@put_url, __FILE__, @bucket, @key)
puts data2.inspect
code2.should == 200
end
end
context ".buckets" do
it "should works" do
code, data = Qiniu::RS::RS.buckets
code.should == 200
puts data.inspect
end
+59
View File
@@ -0,0 +1,59 @@
# Utils.-*- encoding: utf-8 -*-
require 'digest/sha1'
require 'spec_helper'
require 'qiniu/rs/rs'
require 'qiniu/rs/up'
module Qiniu
module RS
describe UP do
before :all do
@localfile = "bigfile.txt"
File.open(@localfile, "w"){|f| 5242888.times{f.write(Random.rand(9).to_s)}}
@bucket = "up_test_bucket"
@key = Digest::SHA1.hexdigest(@localfile+Time.now.to_s)
code, data = Qiniu::RS::RS.mkbucket(@bucket)
puts [code, data].inspect
code.should == 200
end
after :all do
File.unlink(@localfile) if File.exists?(@localfile)
code, data = Qiniu::RS::RS.drop(@bucket)
puts [code, data].inspect
code.should == 200
end
context ".upload_with_token" do
it "should works" do
upopts = {:scope => @bucket, :expires_in => 3600, :customer => "awhy.xu@gmail.com"}
uptoken = Qiniu::RS.generate_upload_token(upopts)
code, data = Qiniu::RS::UP.upload_with_token(uptoken, @localfile, @bucket, @key)
puts data.inspect
(code/100).should == 2
end
end
context ".stat" do
it "should exists" do
code, data = Qiniu::RS::RS.stat(@bucket, @key)
puts data.inspect
code.should == 200
end
end
context ".delete" do
it "should works" do
code, data = Qiniu::RS::RS.delete(@bucket, @key)
puts data.inspect
code.should == 200
end
end
end
end
end
+2 -2
View File
@@ -3,8 +3,8 @@
require 'spec_helper'
require 'qiniu/rs/version'
describe Qiniu::RS do
describe Qiniu::RS::Version do
it "should has a VERSION" do
Qiniu::RS::VERSION.should =~ /^\d+\.\d+\.\d+?$/
Qiniu::RS::Version.to_s.should =~ /^\d+\.\d+\.\d+?$/
end
end
+139 -11
View File
@@ -1,5 +1,6 @@
# -*- encoding: utf-8 -*-
require 'digest/sha1'
require 'spec_helper'
require 'qiniu/rs'
@@ -9,20 +10,93 @@ module Qiniu
before :all do
@bucket = 'qiniu_rs_test'
@key = Digest::SHA1.hexdigest Time.now.to_s
@domain = 'cdn.example.com'
@domain = 'qiniu-rs-test.dn.qbox.me'
result = Qiniu::RS.mkbucket(@bucket)
result.should_not be_false
@test_image_bucket = 'test_images_12345'
result2 = Qiniu::RS.mkbucket(@test_image_bucket)
puts result2.inspect
result2.should be_true
@test_image_key = 'image_logo_for_test.png'
local_file = File.expand_path('./rs/' + @test_image_key, File.dirname(__FILE__))
puts local_file.inspect
upopts = {:scope => @test_image_bucket, :expires_in => 3600, :customer => "awhy.xu@gmail.com"}
uptoken = Qiniu::RS.generate_upload_token(upopts)
data = Qiniu::RS.upload_file :uptoken => uptoken, :file => local_file, :bucket => @test_image_bucket, :key => @test_image_key
puts data.inspect
end
=begin
context ".login!" do
after :all do
result = Qiniu::RS.drop(@bucket)
puts result.inspect
result.should_not be_false
result2 = Qiniu::RS.drop(@test_image_bucket)
puts result2.inspect
result2.should_not be_false
end
context ".buckets" do
it "should works" do
result = Qiniu::RS.login!("test@qbox.net", "test")
result.should be_true
result = Qiniu::RS.buckets
result.should_not be_false
puts result.inspect
end
end
context ".set_protected" do
it "should works" do
result = Qiniu::RS.set_protected(@bucket, 1)
result.should_not be_false
puts result.inspect
end
end
context ".set_separator" do
it "should works" do
result = Qiniu::RS.set_separator(@bucket, "-")
result.should_not be_false
puts result.inspect
end
end
context ".set_style" do
it "should works" do
result = Qiniu::RS.set_style(@bucket, "small.jpg", "imageMogr/auto-orient/thumbnail/!120x120r/gravity/center/crop/!120x120/quality/80")
result.should_not be_false
puts result.inspect
end
end
context ".unset_style" do
it "should works" do
result = Qiniu::RS.unset_style(@bucket, "small.jpg")
result.should_not be_false
puts result.inspect
end
end
context ".set_watermark" do
it "should works" do
options = {
:text => "Powered by QiniuRS"
}
result = Qiniu::RS.set_watermark(1, options)
result.should_not be_false
puts result.inspect
end
end
context ".get_watermark" do
it "should works" do
result = Qiniu::RS.get_watermark(1)
result.should_not be_false
puts result.inspect
end
end
=end
context ".put_auth" do
it "should works" do
@@ -60,6 +134,57 @@ module Qiniu
end
end
context ".upload_file" do
it "should works" do
uptoken_opts = {:scope => @bucket, :escape => 0}
upload_opts = {
:uptoken => Qiniu::RS.generate_upload_token(uptoken_opts),
:file => __FILE__,
:bucket => @bucket,
:key => @key,
:enable_crc32_check => true
}
result = Qiniu::RS.upload_file(upload_opts)
result.should_not be_false
puts result.inspect
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(Random.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 => "awhy.xu@gmail.com", :escape => 0}
uptoken = Qiniu::RS.generate_upload_token(uptoken_opts)
# uploading
upload_opts = {
:uptoken => uptoken,
:file => localfile,
:bucket => @bucket,
:key => key
}
#uploading
result1 = Qiniu::RS.upload_file(upload_opts)
#drop the bigfile
File.unlink(localfile) if File.exists?(localfile)
#expect
puts result1.inspect
result1.should_not be_false
result1.should_not be_empty
#stat
result2 = Qiniu::RS.stat(@bucket, key)
puts result2.inspect
result2.should_not be_false
#delete
result3 = Qiniu::RS.delete(@bucket, key)
puts result3.inspect
result3.should_not be_false
end
end
context ".stat" do
it "should works" do
result = Qiniu::RS.stat(@bucket, @key)
@@ -183,6 +308,9 @@ module Qiniu
puts data.inspect
dest_bucket = "test_thumbnails_bucket"
result = Qiniu::RS.mkbucket(dest_bucket)
result.should_not be_false
dest_key = "cropped-" + @test_image_key
src_img_url = data["url"]
mogrify_options = {
@@ -194,16 +322,16 @@ module Qiniu
:format => "jpg",
:auto_orient => true
}
result = Qiniu::RS.image_mogrify_save_as(dest_bucket, dest_key, src_img_url, mogrify_options)
result.should_not be_false
result.should_not be_empty
puts result.inspect
result2 = Qiniu::RS.image_mogrify_save_as(dest_bucket, dest_key, src_img_url, mogrify_options)
result2.should_not be_false
result2.should_not be_empty
puts result2.inspect
end
end
context ".generate_upload_token" do
it "should works" do
data = Qiniu::RS.generate_upload_token({:scope => 'test_bucket', :expires_in => 3600})
data = Qiniu::RS.generate_upload_token({:scope => 'test_bucket', :expires_in => 3600, :escape => 0})
data.should_not be_empty
puts data.inspect
end
+2 -2
View File
@@ -6,7 +6,7 @@ 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::RS.establish_connection! :access_key => "iN7NgwM31j4-BZacMjPrOQBs34UG1maYCAQmhdCV",
:secret_key => "6QTOr2Jg1gcZEWDQXKOGZh5PziC2MCV5KsntT70j"
end
end